Search code examples
cssangularangular2-directivesangular-router

Is it possible to replace a class with routerLinkActive instead of just adding a class?


I have an icon on a navigation bar which serves as a link to a admin route, I'd like this icon to change when I'm on that specific route, for this I can just replace the mdi-settings-outline class with mdi-settings, which will show a filled version of the same icon.

<li class="nav-item">
    <a routerLink="/admin" routerLinkActive="mdi-settings" class="nav-link mdi mdi-settings-outline"></a>
</li>

However the regular routerLinkActive directive will only add the mdi-settings class to the link, which won't have the desired result. Can the routerLinkActive directive somehow replace the class instead of just adding it?


Solution

  • The routerLinkActive exports some properties that you can use in the template. You access the API by assigning the directive to a template variable. This is done by adding #link="routerLinkActive" where "link" is the name of the variable.

    You can then use the properties of the directive, which are defined here in the API documentation.

    https://angular.io/api/router/RouterLinkActive#properties

    <li class="nav-item">
        <a routerLink="/admin" 
           routerLinkActive="mdi-settings"
           #link="routerLinkActive"
           class="nav-link mdi"
           [class.mdi-settings-outline]="!link.isActive"
        ></a>
    </li>