Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 222
quma Avatar asked Feb 20 '18 10:02

quma


2 Answers

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

like image 54
Paolo Stefan Avatar answered Oct 04 '22 05:10

Paolo Stefan


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.

like image 24
Daniel Albert Avatar answered Oct 04 '22 05:10

Daniel Albert