【问题标题】:How to use *ngIf to test if a variable is defined Ionic 2如何使用 *ngIf 测试变量是否定义 Ionic 2
【发布时间】:2017-05-06 02:50:48
【问题描述】:

有没有办法使用 *ngIf 来测试一个变量是否已定义,而不仅仅是它是否真实?

在下面的示例中,HTML 仅显示红色商品的运费,因为 item.shipping 既已定义又非零。我还想显示蓝色商品的成本(运费已定义但为零),但不显示绿色商品的费用(运费未定义)。

JavaScript:

items = [
      {
        color: 'red',
        shipping: 2,
      },
      {
        color: 'blue',
        shipping: 0,
      },
      {
        color: 'green',
      }
    ];
});

HTML:

<ul *ngFor='let item of items'>
    <li *ngIf='item.color'>The color is {{item.color}}</li>
    <li *ngIf='item.shipping'>The shipping cost is {{item.shipping}}</li>
</ul>

它没有工作。

ERROR 错误:未捕获(承诺中):TypeError:无法读取属性 未定义类型错误的“运输”:无法读取属性“运输”的 未定义

【问题讨论】:

  • 我想在页面上显示 3 个项目,但在 Ionic 3 中显示错误。
  • 我试过 typeof(item.shipping)!==undefined,但它不起作用。请帮我 !谢谢
  • 我(还)从未使用过 Angular.js,但快速查看文档,似乎可以使用相当复杂的条件。我很累,所以没有发布答案,但请查看angular.io/docs/ts/latest/guide/… 以获取提示。
  • 根据错误消息,它说您正在从undefined 检索shipping,我认为这与*ngFor 无关。检查其他部分是否使用item.shippingxxx.shipping

标签: javascript angular ionic-framework


【解决方案1】:

你可以使用这样的东西

<ul *ngFor="let item of items">
    <li *ngIf="item && item.color">The color is {{item.color}}</li>
    ....
</ul>

或使用safe navigation operator

<ul *ngFor="let item of items">
    <li *ngIf="item?.color">The color is {{item.color}}</li>
    ....
</ul>

【讨论】:

  • 谢谢@Tiep Phan &lt;li *ngIf='item?.shipping'&gt;The shipping cost is {{item.shipping}}&lt;/li&gt; 它对我有用!
猜你喜欢
  • 1970-01-01
  • 2011-04-20
  • 2012-12-02
  • 1970-01-01
  • 2012-07-06
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 2011-11-26
相关资源
最近更新 更多