Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

angular - ngClass using evaluated expression drops common classes

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...