简体   繁体   中英

Setting the menu active based on the URL in Angular

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM