简体   繁体   中英

Angular ngClass multiple ternary operator conditions

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?

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'}

While I totally agree with @SamuelMS about explicitly displaying your class names...

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')"

My preferred syntax for ng-class is the following, since it is explicit as to which classes you are adding.

ng-class={ 'className' : yourConditionHere, 'class2' : anotherConditionHere }

Give that a try.

如果您正在使用 angular 8+,则以下内容应该有效。

[ngClass]="{'css-class' : condition1 === true || condition2 === true }">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM