Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set active tab for angular `mat-tab-nav-bar`

I have the following not working code (found in some incomplete example):

<nav mat-tab-nav-bar>
    <a mat-tab-link *ngFor="let device of devices$ | async" [routerLink]="device.getIp()"
        [routerLinkActive #rla="routerLinkActive"
        [active]="rla.isActive">
    </a>
</nav>
<router-outlet></router-outlet>

I am not sure how is this suppose to work:

  • Should I have routerLinkActive defined in my ts?
  • What does [routerLinkActive #rla="routerLinkActive" mean?
like image 564
codentary Avatar asked Mar 25 '26 09:03

codentary


1 Answers

Remove the [ before routerLinkActive, I am not sure whether it is a typo or not, but it is not necessary. I tried to give it a more logical order.

<nav mat-tab-nav-bar>
  <a *ngFor="let device of devices$ | async" 
     [routerLink]="device.getIp()"
     routerLinkActive
     #rla="routerLinkActive"
     mat-tab-link
     [active]="rla.isActive">
  </a>
</nav>
<router-outlet></router-outlet>

That code should be correct. There are some things going on there. So each <a> tag will have the mat-tab-link directive that connects it to mat-tab-nav-bar, and also styles the button, but it needs an input (boolean) that will set it as active or inactive, hence the [active] input. Documentation for it here: https://material.angular.io/components/tabs/examples

Now you need to know how to mark it as active, so [routerLink] input will set the route that link is pointing at, and the routerLinkActive is a directive that will tell whether that route is active or not. Check the API here: https://angular.io/api/router/RouterLinkActive

So what you are doing in your code is, you are assigning that routerLinkActive directive instance to a variable named rla with this #rla="routerLinkActive", then you can access to the isActive property, so you set the input [active] of mat-tab-link to the property in the rla directive instance with [active]="rla.isActive". No need to handle any of that in the ts file.

like image 165
David G. Avatar answered Mar 27 '26 01:03

David G.