1

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?

yer
  • 1,454
  • 2
  • 16
  • 33

3 Answers3

1

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;
}
Nitin Walia
  • 423
  • 2
  • 9
  • may be because i used "active" class name instead of "active-link". can you try [ngClass]="{'active-link':clicked}". – Nitin Walia Jul 09 '18 at 16:04
  • when I'm coming back to home page from details page, this.clicked is showing false – yer Jul 09 '18 at 16:13
  • where did you defined that event and that link? in details component. – Nitin Walia Jul 09 '18 at 17:28
  • that link and event is in home component. – yer Jul 09 '18 at 17:47
  • okay so the reason it is false because when you click that link and redirect to dashboard component, home component get destroyed. That what i think, if this is true then to make it work you have to create a shared service and store that boolean value. – Nitin Walia Jul 09 '18 at 17:54
1

[routerLinkActiveOptions]="{ exact: true } u have eput this one beside the like its work

Raja Reddy
  • 417
  • 2
  • 5
  • 11
0

Solutions :

  1. Can use localStorage to store the information of link clicked.
  2. Can use router queryParams to store the info. Capture the info using ActivatedRoutes :

    this.route.queryParamMap.subscribe( params => { this.enableCard = JSON.parse(params.get('enableCard')); })

Not the best solution, but the work around.

eduPeeth
  • 1,840
  • 13
  • 21