Route Link Active In Angular

In this article, we will figure out how to use routerLinkActive in angular. Router link active class is added when the specific route is activated.

Using routerLinkActive we can easily set an active route. we can toggle CSS classes for dynamic Router Links dependent on the current RouterState.

So, let’s See below example here,

Step 1:-

Create an Angular application using this command

ng new router-link
cd router-link

Step 2:-

Create a Component in your project.

Add following code to app.component.ts

    <li><a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">Home</a></li>
    <li><a routerLink="/product" routerLinkActive="active">Product</a></li>
    <li><a routerLink="/about" routerLinkActive="active">About Us</a></li>
    <li><a routerLink="/contact" routerLinkActive="active">Contect Us</a></li>

Step 3:-

Add following code to app.component.scss

    background-color: rgb(255, 51, 0) !important;
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
li {float: left;}
  li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;

Step 4:-

Add following code to app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AboutComponent } from './about/about.component';
import { ContentUsComponent } from './content-us/content-us.component';
import { RouteLinkActiveComponent } from './route-link-active/route-link-active.component';

const routes: Routes = [
    path: '',
    redirectTo: 'routing',
    pathMatch: 'full'
    path: 'product',
    component: RouteLinkActiveComponent
    path: 'about',
    component: AboutComponent
    path: 'contact',
    component: ContentUsComponent

  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
export class AppRoutingModule { }

You can show the above code we can use routerLinkActive using this we can provide a CSS to the active class.


Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories