6

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?
The DIMM Reaper
  • 3,558
  • 3
  • 28
  • 46
codentary
  • 993
  • 1
  • 14
  • 33

1 Answers1

10

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.

David G.
  • 1,255
  • 9
  • 16
  • 3
    I make a stackblitz with your idea, https://stackblitz.com/edit/angular-o8jf3u?file=src%2Fapp%2Ftab-group-basic-example.html (You're so quicky in response.. :) – Eliseo Nov 21 '19 at 19:53
  • Cool, I was actually looking for a `stackblitz` example before asking here. Thanks. – codentary Nov 21 '19 at 20:16
  • On the stackblitz, I change the property index to 1, but tab /two is not preselected, is this the right way to do it? tnx – Mike Jun 27 '22 at 08:47