NgClass using evaluated expression reduces common classes

When I use ngClass with multiple expressions with common classes, the common class c1 discarded 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 a generic class using the standard class attribute.

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

Is there a better way to achieve this? or is it a bug with angular2?

+5
source share
2 answers

This is not supported.

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

So we say, “I want to have and not have the class foo at the same time,” which obviously makes no sense. This is the order of adding / removing a class, which will lead to different results - this is not something deterministic.

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

Next github discussion

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

1.1: If isOn is true, add the classes active, has-error and has-feedback.

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

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

2.2: If isDisabled evaluates to false, remove classes that are disabled, successful, and have feedback.

It is not possible to track how classes were added to the classList class or who added them, and this does not mean that this is necessary for the ng class. He just applies the rules that he knows about.

+9
source

Why do you want to dynamically apply / delete a class twice? If class c1 always required, add it to the class="c1" attribute and use [ngClass] for any conditional material. Not a mistake, it builds html and css blocks.

0
source

Source: https://habr.com/ru/post/1263329/


All Articles