How could I implement active router link if I have dynamic list of routes and can't assign a fixed route?
I tried to implement a function which on click send index and search in DOM its array position in sidebar.
It works, but when we delete or add one more section, on update, it lost. Maybe someone have another ideas.
Actual code:
A simple way is to use routerLink
to using the routerLinkActive
functionality. A way here is to bind the data like this:
Code
const sections = [{name: "Home", link: ["/home", "other"]},{name: "Contact", link: ["/contact"]}]
HTML
<ul>
<li *ngFor="let link of sections" routerLinkActive="active" [routerLink]="link.link">link.name</li>
</ul>
This is a easy way. And if you don't wanna use routerLink
you need to do it by yourself. One way is to use ngClass
.
You check if the activatedRoute
url is home as example. Then you set a variable to "home" and check it with ngClass
like this:
Code
activeRoute: string = "";
constructor(
private activatedRoute: ActivatedRoute) {
if (activatedRoute.snapshot['_routerState'].url.indexOf("home") > -1) {
this.activeRoute = "home";
}
}
HTML
<ul>
<li *ngFor="let link of sections" [ngClass]="{ active: activeRoute === 'home'}">link.name</li>
</ul>