RRB
RRB

Reputation: 2116

Enable or disable button based on a value

I have a list of buttons like this

<div style="position: absolute; top:0; right: 0;">
 <button class="nav-link-btn" [routerLink]="['/dashboard']"> Dashboard </button>
 <button class="nav-link-btn" [routerLink]="['/admin/templates-dashboard']"  > Templates </button>
 <button class="nav-link-btn" [routerLink]="['/admin/roles-dashboard']" > Users </button>
 <button class="nav-link-btn" [routerLink]="['/corporate/dashboard']"> Corporates </button>
 <button class="nav-link-btn" [routerLink]="['/archive']"> Archive </button>
 <button id="name-btn" class="nav-link-btn" [routerLink]="['/my-profile']"  >
        <span id="circle"></span> {{ name }}
 </button>
 <button  id="logout-btn" (click)="isDialogOpen = true" class="main">Log out</button>
</div>

I then have a user role that is stored in local storage. I am now trying to disable/enable the above buttons based on the users role.

eg if the userRole is a system admin then disable the Archive button but if the userRole is HR Admin then enable the Archive button

I am trying the following but it does not seem to be working as expected

isDisabled(userRole: string): boolean {
    if (userRole == 'System Admin') {
      return true;
    } else {
      return false;
    }
 }

[disabled]="isDisabled(userRole)"

Upvotes: 0

Views: 2690

Answers (1)

wentjun
wentjun

Reputation: 42606

You should still make use of the input bindings and bind the disabled attribute of all buttons to the isDisabled() method. You won't be able to access userRole on your template (component.html) unless you have set it as a property.

<button [disabled]="isDisabled()" class="nav-link-btn" [routerLink]="['/archive']"> Archive </button>

And on your component.ts, you can get the userRole within the isDisabled() method. I am assuming the key is called userRole as well.

isDisabled(): boolean {
    var userRole = storage.getItem(`userRole`);
    if (userRole == 'System Admin') {
      return true;
    } else {
      return false;
    }
 }

Upvotes: 1

Related Questions