Active router link Angular

503 Views Asked by At

How could i implement active router link if i have dymanic list of routes and cant assign a fixed route ? enter image description here

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: enter image description here

1

There are 1 best solutions below

0
Flo On BEST ANSWER

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>