Can ngClass use ternary operator in Angular 2?

前端 未结 3 1092
慢半拍i
慢半拍i 2021-02-02 05:31

In Angular 1, the code below works well.

But when I try to do simi

相关标签:
3条回答
  • 2021-02-02 05:43

    Yes. What you wrote works:

    <div [ngClass]="varA === varB ? 'css-class-1' : 'css-class-2'">
    

    Plunker

    The result of the expression on the the right-hand side has to evaluate to one of the following:

    • a string of space-delimited CSS class names (this is what your expression returns)
    • an Array of CSS class names
    • an Object, with CSS class names as keys, and booleans as values

    Maybe you had some other error in your code?

    0 讨论(0)
  • 2021-02-02 05:45
    <div [ngClass]="{'css-class-1':varA === varB, 'css-class-2': varA !== varB}">
    

    See also https://angular.io/api/common/NgClass

    0 讨论(0)
  • 2021-02-02 05:56

    You can try the followings.....

    For ternary operator use:

    [ngClass]="condition1==condition2?'class-1':'class-2'"
    

    For multiple condition use:

    [ngClass]="{'class-1':condition1==condition2, 'class-2': condition3==condition4}"
    

    thnks...

    0 讨论(0)
提交回复
热议问题