Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Doing an else with ngClass

I have the following template :

<p [ngClass]="{checked: condition, unchecked: !condition}"> 

While this is working, I find it a bit ugly as I have to repeat twice the condition. Is there a way to something like : [ngClass]={condition ? checked : unchecked} (which is not working)

Thanks

like image 483
Scipion Avatar asked Jul 05 '16 12:07

Scipion


People also ask

How do you write if else condition in ngClass?

You can do like this [ngClass]="{'class1':condition1, 'class2':condition2}" .

Can I use both class and ngClass in Angular?

yes , you can do it. Did you try it? What happened? You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.

Can we use NGIF and ngClass together?

javascript - ng-if and ng-class-even/odd doesn't work well together and won't get expected outout - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

Can we add two classes in ngClass?

Using multiple classes is the real reason to use the NgClass directive. You can think of NgClass as being able to specify multiple [class.


1 Answers

Indeed

<p class="{{condition ? 'checked' : 'unchecked'}}"> 

or

<p [ngClass]="condition ? 'checked' : 'unchecked'"> 

or

<p [ngClass]="[condition ? 'checked' : 'unchecked']"> 

Angular 9 Update

But you should know that there's a difference in how different types of class bindings behave, especially when there are multiple types of class bindings on the same element.

And the new compiler, Ivy, brings more clarity and predictability to it. Read More about it here

like image 54
Ankit Singh Avatar answered Sep 16 '22 11:09

Ankit Singh