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>