Disable router navigate link based on conditions

1.9k Views Asked by At

How can I disable the router.navigate or the link, based on a status?

If the status is a "No" then i can't type the link to edit the Materials?

HTML

<button type="button" (click)="onEditMaterial(material.id)">Edit </button>

TS

onEditMaterial(material_id) {
  this.router.navigate(['materials', material_id, 'edit']);
}
2

There are 2 best solutions below

15
On

<button [attr.disable]="status === 'No'">click me</button> .status is a string in your angular component. <button [disable]="status === 'No'">click me</button> syntax.

Edit: disable attribute is a HTML5 attribute used for <input> , <button> etc. You can make it look nicer for better UX with some css as well like this: button:disabled {cursor: not-allowed;}

Edit: another way is something like this

onEditMaterial(material_id) {
    if (this.status === 'No') return; // if the status is 'No' don't do anything

    this.router.navigate(['materials', material_id, 'edit']);
  }
0
On

To disable the button, you can follow the answer provided by DrNio. There based upon the conversation in comment, if you also want to prevent navigation even with changing URL in browser then you need to use Router Guard. Check an example of AuthGuard here: https://angular.io/guide/router#component-less-route-grouping-routes-without-a-component . Search for export class AuthGuard implements CanActivate. You basically need to implement canActivate method.