angular - 使用求值表达式的 ngClass 删除通用类

标签 angular

当我将 ngClass 与具有公共(public)类的多个表达式一起使用时,当表达式从 false 变为 true 时,公共(public)类 c1 被删除:

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

为了克服这个问题,我必须使用标准的 class 属性指定公共(public)类。

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

有没有更好的方法来实现这一点?还是 Angular2 的错误?

最佳答案

不支持。

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}".

深入github讨论

[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.

关于angular - 使用求值表达式的 ngClass 删除通用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41853998/

相关文章:

html - Angular2 ng-模板

javascript - 如何创建一个 Countup 计时器 Angular 5

angular - 动态添加和删除 Angular 5 Material 属性 'multiple'

css - Angular 4 - Material 主题定制

javascript - 如何停止 javascript++ 或 - - 条件

javascript - Angular 2( ionic 2): can't "render" Component inside Page

valueChanges 上的 Angular 7 FormControl 获得旧值

Angular 性能跟踪

javascript - 是否可以在类位于 Angular 6 组件内部的应用程序组件上使用 [ngClass]?

jquery - Angular 4 : jQuery and angular2-materialize not working after route navigation