How to change the state of a routerLink to a route whose navigation is prevented by a guard

Discussão em 'Angular' iniciado por Pragmateek, Maio 8, 2025.

  1. Pragmateek

    Pragmateek Guest

    If I have a route like:

    export const routes: Routes = [
    {
    path: 'phony',
    component: PhonyComponent,
    canActivate: [() => inject(PhonyService).ok]
    }
    ];


    And a routerLink pointing to it:

    <a routerLink="/phony">Go to Phony</a>


    The guard is called as expected when the navigation is attempted and prevents it when needed.

    But the link always looks the same.

    Is there a builtin mechanism to mark the link as disabled when the navigation cannot be done?
    Ideally something like RouterLinkActive which applies a CSS class if the link matches the current route, but in this case when the navigation to its target is allowed (or not).

    A workaround is replicating the guard's condition:

    <a [class.disabled]="!phonyService.ok" routerLink="/phony">Go to Phony</a>


    But it creates coupling.
    Of course, it could be refined to expose a global canNavigateToPhony function that would be called both by the guard and the link, but it forces to design to compensate for a feature that would be easily provided by the Angular runtime which handles routing.

    Continue reading...

Compartilhe esta Página