Angular 13 and above
[routerLink]="null"
(and undefined
) is now officially used to disable the routerLink
.
(see Docs)
So this is enough:
<a [routerLink]="linkEnabled ? 'path' : null">Link</a>
Angular 12 and below
[routerLink]="null"
(and undefined
) is treated as a shorthand for an empty array of commands. So it makes the routerLink
to link to the current/active route. This behavior allows us to abuse the routerLinkActive
directive for our purpose:
Template:
<a [routerLink]="linkEnabled ? 'path' : null"
[routerLinkActive]="linkEnabled ? 'is_active' : 'is_disabled'">Link</a>
Optional CSS:
.is_disabled {
cursor: default;
text-decoration: none;
}
.is_active {
// your style for active router link
}
Live demo (Angular 10):
See demo on StackBlitz
Detailed Description:
When linkEnabled
returns false
, null
will make routerLink
to link to the current/active route.
If routerLink
links to the active route, the class which is specified in routerLinkActive
will be applied. That will be is_disabled
in this case.
There we can specify, how the disabled routerLink should appear.
routerLink
to the active route won't trigger a navigation event.