Search code examples
angularangular12

¿How to change mat-icon color based on routerLinkActive state Angular?


I've this component called "nav-menu" and here we can see every option for the mat-list navigation. I want to change mat-icon color when the routerLink is active. I tried to use ngIf and ngClass but don't work.

This is the code:

<mat-nav-list>
        <a  *ngFor="let option of options"
            [routerLink]="[option.route]"
            mat-list-item routerLinkActive #routerLink="routerLinkActive">
            <mat-icon matListIcon 
                [ngClass]="{'material-icons-outlined': !routerLink.isActive}"
                color=''> //here set primary is the routerLink is active
                {{option.icon}}
            </mat-icon>
        </a>
</mat-nav-list>

Solution

  • The solution was use ternary operation and verify the routerLink state.

    Here's the code:

    <mat-nav-list>
        <a  *ngFor="let option of options"
            [routerLink]="[option.route]"
            mat-list-item 
            routerLinkActive #routerLink="routerLinkActive">
            <mat-icon matListIcon 
                [ngClass]="{'material-icons-outlined': !routerLink.isActive}"
                color="{{routerLink.isActive ? 'primary' : ''}}"> // Here's the solution
                {{option.icon}}
            </mat-icon>
        </a>
    </mat-nav-list>