quma
quma

Reputation: 5753

Angular Material - set button active

I use this navigation in my Angular 5/Angular Materials application:

<!-- Navigation -->
<mat-toolbar color="warn">  
 <mat-toolbar-row>
  <span class="nav-icon">
    My Icon
  </span>

  <span class="nav-spacer"></span>

  <button mat-button [routerLink]="['/home']">Home</button> 
  <button mat-button [routerLink]="['/login']">Login</button>
  <button mat-button (click)="logout()">Logout</button>
 </mat-toolbar-row>
</mat-toolbar>

<!-- Router Outlet -->
<router-outlet></router-outlet>

Actually I could not find how to set the active menu button active. Is there a way of doing this, e.g. with Route?

Upvotes: 10

Views: 23319

Answers (2)

Paolo Stefan
Paolo Stefan

Reputation: 10283

In Angular 6 you can add the routerLinkActive attribute to buttons. When the corresponding route is the current one, the content of this attribute will be added to the element's css classes.

For example:

<button mat-button [routerLink]="['/home']" routerLinkActive="mat-accent">
    Home
</button>

When this button is clicked and the corresponding route becomes the active one, it will get the additional mat-accent CSS class.

Reference: Angular.io docs, Angular API docs

Upvotes: 30

Daniel Albert
Daniel Albert

Reputation: 76

Hopefully, this helps someone the active class was not working for me I'm using Angular version 12.0.5

I replaced:

<button mat-raised-button routerLink="/overview/anxietydepressionchart/{{id}}" routerLinkActive="activebutton">Anxiety Depression Graph</button>

With:

<a mat-raised-button routerLink="/overview/anxietydepressionchart/{{id}}" routerLinkActive="activebutton" >Anxiety Depression Graph</a>

CSS:

.activebutton 
{
  background-color: rgb(51, 51, 51);
  color: white;
}

This solved my active button issues.

Upvotes: 1

Related Questions