angularrouterlinkrouterlinkactive

Add active class to routerlink in angular 4


I would like to add an active class when changing routes. I have an link in one component (home page) which redirects to other component (details page).

<a routerLink="/dashboard/details" (click)="Clicked()"</a>

Now when I return back from details page to home page, I want to have the a link to be active telling the users that this link has been clicked.

I tried using routerLinkActive, but that doesn't seem to be working.

html

<a routerLink="/dashboard/details" routerLinkActive="active-link" (click)="Clicked()"</a>

css

.active-link {
    color:red;
    font-weight: bold;
}

Can anyone help me with this?


Solution

  • Why don't you add class name on click event. try this.

    <a routerLink="/dashboard/details" [ngClass]="{'active-link':clicked}" routerLinkActive="active-link" (click)="Clicked()"</a>
    

    in .ts file

    clicked: boolean = false;
    
    Clicked() {
    this.clicked = true;
    }