Luca
Luca

Reputation: 348

take the name/path of the current route

i have this navbar:

 <nav class="menu">
   <a routerLink="textArea" class="menu-item">text-area</a>
   <a routerLink="dropdown" class="menu-item">dropdown</a>
   <a routerLink="autosuggest" class="menu-item">autosuggest</a>
   <a routerLink="manageCookies" class="menu-item">manage-cookies</a>
   <a routerLink="progressBar" class="menu-item">progress-bar</a>
 </nav>
 <router-outlet></router-outlet>

and the routes declared in the app.routing:

 const routes: Routes = [
   {
     path: 'textArea',
     component: TextAreaComponent,
   },
   {
     path: 'dropdown',
     component: DropdownComponent,
   },
   {
    path: 'autosuggest',
    component: AutosuggestComponent,
   },
   {
     path: 'manageCookies',
     component: ManageCookiesComponent,
   },
   {
     path: 'progressBar',
     component: ProgressBarComponent,
   },
 ];

I would like to apply a class to the navbar if the route where I click is, for example, progressBar ... what do I do? To be clear, I would do something like this:

 <nav class="menu" [class.myClass]="currentRoute === 'progressBar'">
   .......
 </nav>

Upvotes: 0

Views: 59

Answers (2)

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

This is how you should use the router module, you can pass any number of classes in the routerLinkActive. You can check here for more details.

 <nav class="menu">
   <a routerLink="textArea" [routerLinkActive]="['is-active', 'class 1']" class="menu-item">text-area</a>
   <a routerLink="dropdown" [routerLinkActive]="['is-active']" class="menu-item">dropdown</a>
   <a routerLink="autosuggest" [routerLinkActive]="['is-active']" class="menu-item">autosuggest</a>
   <a routerLink="manageCookies" [routerLinkActive]="['is-active']" class="menu-item">manage-cookies</a>
   <a routerLink="progressBar" [routerLinkActive]="['is-active']" class="menu-item">progress-bar</a>
 </nav>

If you want to do it dynamically, you can do something like this:

 <nav class="menu" [ngClass]="urlBased">
   .......
 </nav>

In your Ts file add a method to populate urlBased based on route activated:

// Sample code to follow
 constructor(private router: Router) {
          router.events.subscribe((url:any) => { 
          console.log(url)); // url will be the path or use this.router.url
          //this.urlBased = this.router.url;
          this.urlBased = url;
           if(this.urlBased && this.urlBased.length > 0){
            this.urlBased = this.urlBased.slice(1);
            if (this.urlBased == 'progressBar') this.urlBased = progressBar;
          }
   }
  }

Upvotes: 1

Johna
Johna

Reputation: 1894

You can use routerLinkActive property directly together with routerLink.

<a routerLink="textArea" [routerLinkActive]="['myClass']">text-area</a>
<a routerLink="dropdown" [routerLinkActive]="['myClass']">dropdown</a>

Upvotes: 1

Related Questions