Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngClass using evaluated expression drops common classes

Tags:

angular

When I use ngClass with multiple expressions with common classes, the common class c1 is dropped when the expression changes from false to true:

<span [ngClass]="{'c1 c2' : showTwo, 'c1 c3' : showThree, 'c1 c4' : showFour}" ></span>

To overcome this I have to specify the common class using the standard class attribute.

<span class="c1" [ngClass]="{'c2' : showTwo, 'c3' : showThree, 'c4' : showFour}" ></span>

Is there a better way of achieving this? or is it a bug with Angular2?

like image 212
Christopher Moore Avatar asked Jan 25 '17 14:01

Christopher Moore


People also ask

Can you use ngClass and class?

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.

How do you remove a class from ngClass?

In ngClass directive either you can just pass the $scope variable which contains the classes or use the expressions to add or remove the class. ng-class="{class-name: expression1, class-name: expression2, ...}"

How do I add a class to ngClass?

To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.


1 Answers

That's not supported.

https://github.com/angular/angular/issues/5763#issuecomment-163710342

So we are kind of saying "I want to have and not have foo class at the same time" which obviously doesn't make sense. It is an order of class addition / removal that will lead to different results - this is not something deterministic.

I guess you need to change your code to be sth like: [ng-class]="{'active has-error': isOn, 'disabled has-success': isDisabled, 'has-feedback': isOn || isDisabled}".

Further down the github discussion

[ng-class]="{'active has-error has-feedback': isOn, 'disabled has-success has-feedback': isDisabled}" can be broken down to:

1.1: If isOn evaluates to true, add classes active, has-error and has-feedback.

1.2: If isOn evaluates to false, remove classes active, has-error and has-feedback.

2.1: If isDisabled evaluates to true, add classes disabled, has-success and has-feedback.

2.2: If isDisabled evaluates to false, remove classes disabled, has-success and has-feedback.

There is no way to keep track of how the classes were added to the element's classList or who added them and it's not ng-class' purpose to do so. It just applies the rules it knows about.

like image 136
Günter Zöchbauer Avatar answered Nov 03 '22 18:11

Günter Zöchbauer