【问题标题】:Angular ngClass multiple ternary operator conditionsAngular ngClass 多个三元运算符条件
【发布时间】:2015-08-29 16:37:01
【问题描述】:

在 Angular 的 ngClass 指令中放置多个三元条件类的最佳方法是什么,其中值是类名?

我已经尝试了一些变体,但我总是得到一个编译错误:

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

【问题讨论】:

    标签: javascript angularjs ternary-operator


    【解决方案1】:

    虽然我完全同意 @SamuelMS 关于明确显示您的班级名称...

    如果你真的想使用多个三元运算符(或者只是好奇),你可以这样做:

    ng-class="($index > 2 ? 'l3 m4 s12 medium' : 'l4 m6 s12 medium') + ' ' + (true ? 'red' : 'blue')"
    

    【讨论】:

    • 哈哈,这是一个不错的方法。我绝对可以看到为什么@SamuelMS 方法更好,但这很有帮助,谢谢!
    【解决方案2】:

    我对 ng-class 的首选语法如下,因为它明确说明您要添加哪些类。

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

    试试看。

    【讨论】:

    • 谢谢,我想看看是否有办法将类名作为三元运算符的值。
    【解决方案3】:

    如果您正在使用 Angular 8+,则以下内容应该可以工作。

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

    【讨论】:

      猜你喜欢
      • 2013-06-06
      • 2012-09-14
      • 2011-06-26
      • 1970-01-01
      • 2013-01-14
      • 2016-05-15
      • 2020-05-18
      • 2016-11-02
      • 2020-01-18
      相关资源
      最近更新 更多