0

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

peinearydevelopment
  • 11,042
  • 5
  • 48
  • 76
dunivivi
  • 1
  • 3
  • What is your problem? You don't need to add the "active" class by hand. This does `routerLinkActive` itself. And dynamically creating is not a problem. – Flo Feb 20 '23 at 18:58
  • @Flo, it does not, as I saw, without passing routerlink :/ – dunivivi Feb 20 '23 at 19:05
  • Ah I see you don't set routerLink in the html element. Then it will not working, that's right. use `ngClass` instead .classList.add() and it will work, too – Flo Feb 20 '23 at 19:18
  • @Flo, ngClass would not add class for all the a tags in *ngfor? – dunivivi Feb 21 '23 at 04:28
  • Or you mean to pass it in typescript ? – dunivivi Feb 21 '23 at 04:29
  • Yes, use `ngClass` or you can add the `routerLink` and bind it in each element. Then the `routerLinkActive` will do its job. – Flo Feb 21 '23 at 06:45
  • @Flo, thank you so much !!! [routerLink]="['/document', section.id, section.recordType]" in HTML, works! – dunivivi Feb 21 '23 at 07:01

1 Answers1

0

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>
Flo
  • 2,232
  • 2
  • 11
  • 18