javascript Angular ngClass 多三元运算符条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30823885/
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
Angular ngClass multiple ternary operator conditions
提问by d-_-b
What is the best way to put more than 1 ternary conditional class in angular's ngClass
directive, where the values are the class-names?
在 angular 的ngClass
指令中放置 1 个以上的三元条件类的最佳方法是什么,其中值是类名?
I've tried a few variations on this, but i always get a compiling error:
我已经尝试了一些变体,但我总是遇到编译错误:
ng-class="$index > 2 ? 'l3 m4 s12 medium' : 'l4 m6 s12 medium', true ? 'red':'blue'
ng-class="$index > 2 ? 'l3 m4 s12 medium' : 'l4 m6 s12 medium', true ? 'red':'blue'
ng-class="{$index > 2 ? 'l3 m4 s12 medium' : 'l4 m6 s12 medium', true ? 'red':'blue'}
ng-class="{$index > 2 ? 'l3 m4 s12 medium' : 'l4 m6 s12 medium', true ? 'red':'blue'}
回答by sfletche
While I totally agree with @SamuelMS about explicitly displaying your class names...
虽然我完全同意@SamuelMS 关于明确显示您的班级名称的看法......
If you really want to use multiple ternary operators (or are simply curious) you can do so like this:
如果你真的想使用多个三元运算符(或者只是好奇),你可以这样做:
ng-class="($index > 2 ? 'l3 m4 s12 medium' : 'l4 m6 s12 medium') + ' ' + (true ? 'red' : 'blue')"
回答by SamuelMS
My preferred syntax for ng-class is the following, since it is explicit as to which classes you are adding.
我首选的 ng-class 语法如下,因为它明确说明了您要添加哪些类。
ng-class={ 'className' : yourConditionHere, 'class2' : anotherConditionHere }
Give that a try.
试一试吧。
回答by Hamfri
If you are working on angular 8+ the following should work.
如果您正在使用 angular 8+,以下应该可以工作。
[ngClass]="{'css-class' : condition1 === true || condition2 === true }">