RRB
RRB

Reputation: 2116

Add multiple values to disabled attribute in Angular

I am trying to add values to a disabled directive. So if you look at the code below I am disabling a button if a value matches System Admin. I am now trying to add more values to this. So I want to add System Admin and HR Manager to this.

[disabled]="userRole === 'System Admin'"

I tried this but it does not seem to work

[disabled]="userRole === 'System Admin' || 'HR Manager'"

Upvotes: 3

Views: 3080

Answers (4)

Yash Rami
Yash Rami

Reputation: 2317

You can try like this.

[disabled]="(userRole === 'System Admin' || userRole === 'HR Manager') ? true : false"

Upvotes: 1

Adrita Sharma
Adrita Sharma

Reputation: 22203

If you have many conditions to check then its better to write a function which will return true or false:

HTML:

[disabled]="isDisabled(userRole)"

Typescript:

isDisabled(userRole:string):boolean {
  if(userRole == "System Admin" || userRole == "HR Manager") {
    return true
  }
  return false
} 

Upvotes: 4

Prashant Pimpale
Prashant Pimpale

Reputation: 10707

You can't compare one thing with multiple things if that are strings (as per my knowledge), so need to modify the condition like this:

[disabled]="userRole === 'System Admin' || userRole === 'HR Manager'"

The problem with Custom function to disable the control, it calls multiple times (Called even if you click on the control):

enter image description here

So if there are only two values to compare then I would use HTML Code Approach

Stackblitz_Demo

Upvotes: 1

Vahid
Vahid

Reputation: 7561

The reason is that:

userRole === 'System Admin' || 'HR Manager'

means

if (userRole === 'System Admin') return true;
else return 'HR Manager';

So you can use this:

['System Admin','HR Manager'].indexOf(userRole) !== -1

Upvotes: 1

Related Questions