3

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'"
1
  • Hope it will work if you add parentheses [disabled]="(userRole === 'System Admin' || 'HR Manager')" Commented May 10, 2019 at 10:32

4 Answers 4

4

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
} 
Sign up to request clarification or add additional context in comments.

3 Comments

NVM, But in this way we are having a performance issues bcs isDisabled is continuously call when ever the change is detected.
@YashRami Since it is in a loop, whenever change is detected, ternary operator condition will also be continuously called. As per my knowledge, calling the function won't create any additional performance issue, it's same even if it is written in view
@AdritaSharma If you loop over 1000 records then It actually blocks the UI and makes page unresponsive! See demo here
1

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

Comments

1

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

Comments

1

You can try like this.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.