0

I am working on an angular app with a top menu and i need to set the menu active based on the url. Here is what i have tried.

URL example

http://localhost:4200/home/about - About should be highlighted

http://localhost:4200/home/service/supply - Service should be highlighted

http://localhost:4200/home/contact/details- Contact should be highlighted

    if (event instanceof NavigationStart) {
      this.currentMenu = this.elem.nativeElement.querySelectorAll('.nav-link'); 
      for (let i = 0; i < this.currentMenu.length; i++) {
        if(event.url.indexOf('/about') > -1){
          if(this.currentMenu[i].innerHTML == "About"){
            this.currentMenu[i].style.color  = "red";
          } 
        } else if (event.url.indexOf('/service') > -1){
          if(this.currentMenu[i].innerHTML == "Service"){
            this.currentMenu[i].style.color  = "red";
          } 
        }
        else if (event.url.indexOf('/contact') > -1){
            if(this.currentMenu[i].innerHTML == "Contact"){
              this.currentMenu[i].style.color  = "red";
            } 
          }
      }
    }
  })

I am not sure whether this is the right approach to achieve this. any inputs will be highly appreciated

Sha
  • 1,826
  • 5
  • 29
  • 53

1 Answers1

0

No need to do the long way you've done as the Angular Library provides an easy and efficient solution to this.

Since you said you're dealing with Menu options, please use routerLinkActive and routerLinkActiveOptions directives here as below: -

Option 1:

<a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>

Option 2:

<a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a>
<a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a>

Option 3:

<div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
  <a routerLink="/user/jim">Jim</a>
  <a routerLink="/user/bob">Bob</a>
</div>

Use as per your requirements. More details can be found here: https://angular.io/api/router/RouterLinkActive#routerlinkactive

Santhosh John
  • 648
  • 5
  • 14