【问题标题】:Dealing with null values in angular (9) ngFor在 Angular (9) ngFor 中处理空值
【发布时间】:2020-09-08 22:59:05
【问题描述】:

我有一个由 ngFor 填充的表。

我正在使用类似的东西:

{{ (item.attribute || "--" }}

处理空值并且工作正常但是我有一个显示倍数的字段,所以我在其中添加了一个“x”:

{{ (item.attribute + "x") || "--" }}

显然,“x”给了它一个值,因此即使属性为空,html 也会显示一个“x”而不是我喜欢的“--”。

我想我可能需要使用 ngIf,但我无法让任何实现工作。谁能指出我正确的方向?

提前致谢。

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    您可以在此处使用 Javascript 三元运算符根据逻辑条件发出不同的值。

    {{item.attribute ? item.attribute + "x" : '--'}}
    

    演示:https://stackblitz.com/edit/angular-u8ly3l

    【讨论】:

      【解决方案2】:

      您可以在模板中使用三元运算符:\

      {{ item.attribute ? item.attribue + "x" : "--" }}
      

      这将检查item.attribute 是否为真,如果是,它将返回item.attribute 与“x”连接。

      【讨论】:

        【解决方案3】:

        试试这个

        您可以在模板内部使用条件(三元)运算符,如下例所示

        {{ item.attribute? (item.attribute + "x"): "--" }}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-06-25
          • 1970-01-01
          • 2020-11-04
          • 2017-11-03
          • 2020-08-25
          • 1970-01-01
          • 2021-01-08
          • 2021-03-10
          相关资源
          最近更新 更多