How can I conditionally disable the routerLink attribute?

我怕爱的太早我们不能终老 提交于 2019-11-26 22:37:38

Disabling pointer-events on the

<a [routerlink]="xxx" [class.disabled]="disabled ? true : null">Link</a>

a.disabled {
   pointer-events: none;
   cursor: default;
}

See also Angular2, what is the correct way to disable an anchor element?

or

<a *ngIf="isEnabled" [routerlink]="xxx">Link</a>
<div *ngIf="!isEnabled">not a link</div>

or to easily reuse the disabled link template

<ng-template #disabledLink>
  <div *ngIf="!isEnabled">not a link</div>
</ng-template>
<a *ngIf="isEnabled; else disabledLink" [routerlink]="xxx">Link</a>

No need to disable any pointer events:

Template:

<a [routerLink]="homeLinkEnabled ? '/home' : null" routerLinkActive="is-active">Home</a>

Optional CSS:

.is-active {
    cursor: default;
    text-decoration: none;
}

Description:

When homeLinkEnabled 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.

There we can specify, how the disabled routerLink should appear.

routerLink to the active route won't trigger a navigation event.

I've just had some success with a similar issue: having an array of nav links in an ngFor, some required [routerLink], while others required (click) - my issue was that all links relied on [routerLink] for [routerLinkActive], so I had to stop routerLink, without touching it's value.

`<a [routerLink]="item.link" routerLinkActive="isActive">
    <span (click)="item.click ? item.click($event) : void>
</a>`

with:

`click: ($event) => {
    $event.stopPropagation(); // Only seems to
    $event.preventDefault(); // work with both
    // Custom onClick logic
}`

As the span is inside, you can be sure the cancelling of the event happens before it bubbles up to [routerLink], while routerLinkActive will still apply.

Disabling pointer-events on any html tag:

<div [routerLink]="['/home', { foo: bar }]"
     [ngStyle]="{'pointer-events': myLinkEnabled ? 'none' : null}">
     Click me
</div>

'none' resolves to disabling pointer-events, that is, disabling the link.

null resolves to ignore the style.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!