One of the easiest ways to implement dynamic routing in Angular is by utilizing routerLink
along with the routerLinkActive
functionality. You can achieve this by binding data in the following manner:
Sample Code
const sections = [{name: "Home", link: ["/home", "other"]},{name: "Contact", link: ["/contact"]}]
HTML Implementation
<ul>
<li *ngFor="let link of sections" routerLinkActive="active" [routerLink]="link.link">{{ link.name }}</li>
</ul>
This approach offers a straightforward solution. However, if you prefer not to use routerLink
, you can handle it manually. One method involves using ngClass
to dynamically add classes based on certain conditions.
Example Code
activeRoute: string = "";
constructor(
private activatedRoute: ActivatedRoute) {
if (activatedRoute.snapshot['_routerState'].url.indexOf("home") > -1) {
this.activeRoute = "home";
}
}
HTML Integration
<ul>
<li *ngFor="let link of sections" [ngClass]="{ active: activeRoute === 'home'}">{{ link.name }}</li>
</ul>