How to apply multiple ngIf conditions in Angular syntax?

Viewed 228

I need set multiple conditions in ngIf statement.

I have create Template for multiples users but some content i don't want to see for particular users like Super Admin, Admin, Section Users, Division User and Unit Leaders.

enum of users: ['s','a','d','u','c']

1> Super Admin -> s
2> Admin -> a
3> Division Supervisor -> d
4> Unit Leader -> u
5> Section Chief -> c

For example I want to show below button for just particular user login i tried below code work fine for two users but

<button *ngIf="menuUserType === 'a' || menuUserType !== 's' " class="btn-style red-btn" routerLink="/division/add-edit-division/0"><span class="material-icons">add</span>Add Division</button>

But when i try to apply for more user its not work and i get errors.

<button *ngIf="menuUserType === 'a' || menuUserType === 'c' || menuUserType !== 's' || menuUserType !== 'd'  " class="btn-style red-btn" routerLink="/division/add-edit-division/0"><span class="material-icons">add</span>Add Division</button>

Error

enter image description here

So is there any solutions for that?

2 Answers

Your second if is wrong, because the letter A and C is different of the letter S. And another thing that you are doing is if the variable is different than S and in the same time D, so Angular will show you an error that it will be always true because whatever letter that you use will be true. What you need is just this:

<button *ngIf="menuUserType !== 's' && menuUserType !== 'd'" class="btn-style red-btn" routerLink="/division/add-edit-division/0"><span class="material-icons">add</span>Add Division</button>

Yes , That is bound to happen . Because when you are writing menuUserType === 'a' || menuUserType === 'c' and then specifying menuUserType !== 's' || menuUserType !== 'd' , which means it will always either be a , c or u . ( Which the error says it will always be true )

So no need of specifying multiple conditions with === and !-- .

You can directly specify only !== or == condition .

<button *ngIf="menuUserType !== 's' && menuUserType !== 'd'" class="btn-style red-btn" routerLink="/division/add-edit-division/0"><span class="material-icons">add</span>Add Division</button>

Which will automatically mean it is equal to anything apart from s and d .

Related