处理 angular 中的空值 (9) ngFor

Dealing with null values in angular (9) ngFor

我有一个 table 由 ngFor 填充。

我正在使用类似的东西:

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

处理空值,这很好用,但是我有一个显示倍数的字段,所以我在其中添加了一个 "x":

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

显然 "x" 给了它一个值,因此即使属性为空,html 也会显示 'x' 而不是我首选的 '--'。

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

提前致谢。

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

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

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

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

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

这将检查 item.attribute 是否为真,如果是,它将 return item.attribute 与 "x" 连接。

试试这个

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

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