如何在ngStyle中应用布尔函数

huangapple go评论136阅读模式
英文:

How to apply Boolean functions in ngStyle

问题

    <div *ngFor="let singleorder of order.order">
        <p [ngStyle]="{
          'color': (singleorder.status === 'CONFIRM') ? 'green' : 'red',
          'background': (singleorder.status === 'CONFIRM') ? '#e4f4eb' : '#f7d0c7'
        }">{{singleorder.status}}</p>
    </div>
英文:
&lt;div *ngFor= “ let singleorder of order.order”&gt;
    &lt;p [ngStyle]=&quot;
      &#39;color&#39;:(single order.status === &#39;CONFIRM&#39; )? &#39;green&#39; : &#39;red&#39; ,
       &#39;background&#39; : (single order.status === &#39;CONFIRM&#39;)? &#39;#e4f4eb&#39;: &#39;#f7d0c7&#39;
    }&quot;&gt;. {{single order.status}}&gt;

&lt;/div&gt;

I am expecting the background color and color to be green when the value of status is CONFIRM and also show red when the value is CANCELLED

答案1

得分: 0

根据文档,这是正确的语法(请注意大括号)。

&lt;p [ngStyle]="{
  'color': singleorder.status === 'CONFIRM' ? 'green' : 'red',
  'background': singleorder.status === 'CONFIRM' ? '#e4f4eb' : '#f7d0c7'
}"&gt;
  {{singleorder.status}}&gt;
&lt;/p&gt;

由于你正在基于相同条件设置多个样式属性,可能更清晰的做法是定义几个CSS类并使用[`ngClass`](https://angular.io/api/common/NgClass)或[class绑定](https://angular.io/guide/class-binding)。
英文:

Based on the documentation, this is the correct syntax (note the curly braces).

&lt;p [ngStyle]=&quot;{
  &#39;color&#39;: singleorder.status === &#39;CONFIRM&#39; ? &#39;green&#39; : &#39;red&#39;,
  &#39;background&#39;: singleorder.status === &#39;CONFIRM&#39; ? &#39;#e4f4eb&#39;: &#39;#f7d0c7&#39;
}&quot;&gt;
  {{singleorder.status}}&gt;
&lt;/p&gt;

Since you're basing multiple style properties on the same condition, it would probably be cleaner to define a couple of CSS classes and use ngClass or use class binding.

huangapple
  • 本文由 发表于 2023年3月9日 16:06:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定