Html Angular 2 用 ngClass 做一个 else

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38203030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:30:59  来源:igfitidea点击:

Angular 2 Doing an else with ngClass

htmlangularng-class

提问by Scipion

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)

虽然这是有效的,但我发现它有点难看,因为我必须重复两次条件。有没有办法像:([ngClass]={condition ? checked : unchecked}这是行不通的)

Thanks

谢谢

回答by Ankit Singh

Indeed

的确

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

or

或者

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

or

或者

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


Angular 9 Update

Angular 9 更新

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

新的编译器 Ivy 为它带来了更多的清晰度和可预测性。在此处阅读更多相关信息