Angular 6 Material: mat-tab-link be selected by underlining bar
It doesn't work for you because every has the same #rla variable
You can do it this way:
<nav mat-tab-nav-bar>
<a mat-tab-link
*ngFor="let link of navLinks"
[routerLink]="link.path"
routerLinkActive #rla="routerLinkActive"
[active]="link.isActive">
{{link.label}}
</a>
</nav>
<router-outlet></router-outlet>
or with {exact:true}
<nav mat-tab-nav-bar>
<a mat-tab-link
*ngFor="let link of navLinks"
[routerLink]="link.path"
routerLinkActive #rla="routerLinkActive"
[routerLinkActiveOptions]="{exact:true}"
[active]="rla.isActive">
{{link.label}}
</a>
</nav>
<router-outlet></router-outlet>
You're missing a /
before the link:
<nav mat-tab-nav-bar>
<a mat-tab-link
*ngFor="let link of navLinks"
[routerLink]="['/'+link.path]"
routerLinkActive #rla="routerLinkActive"
[active]="rla.isActive">
{{link.label}}
</a>
</nav>
<router-outlet></router-outlet>
EDIT: The right way here is to set a non-empty path for all routes. You can then use a wildcard with a redirect.
const APP_ROUTES: Route[] = [
{ path: 'path-1', component: OneComponent },
{ path: 'path-2', component: TwoComponent },
{ path: 'path-3', component: ThreeComponent },
{ path: '**', redirectTo: 'path-1' },
]
You need to add [routerLinkActiveOptions]="{exact:true}"
to the a
tag.
It becomes
<nav mat-tab-nav-bar>
<a mat-tab-link
*ngFor="let link of navLinks"
[routerLink]="link.path"
routerLinkActive #rla="routerLinkActive"
[routerLinkActiveOptions]="{exact:true}"
[active]="rla.isActive">
{{link.label}}
<div style="color: red; margin-left: 10px;">
<span *ngIf="rla.isActive"> Is active!</span>
<span *ngIf="!rla.isActive"> Is not active...</span>
</div>
</a>
</nav>
<router-outlet></router-outlet>
Using different local variables(#rla1
, #rla2
) worked for me, as i was not using *ngFor
:
<nav mat-tab-nav-bar>
<a mat-tab-link
[routerLink]="['/home/homepage/dashboard/']"
routerLinkActive #rla1="routerLinkActive"
[active]="rla1.isActive">Dashboard
</a>
<a mat-tab-link
[routerLink]="['/home/homepage/reports/']"
routerLinkActive #rla2="routerLinkActive"
[active]="rla2.isActive">Reports
</a>
</nav>