2017-05-06 22 views
2

有没有一种方法可以使用* ngIf来测试一个变量是否被定义,而不仅仅是它是否真实?如何使用* ngIf来测试变量是否被定义Ionic 2

在下面的示例中,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 Error: Uncaught (in promise): TypeError: Cannot read property 'shipping' of undefined TypeError: Cannot read property 'shipping' of undefined

+0

我想在页面上显示3个项目,但它显示在离子3. – AdminDev826

+0

我的错误尝试typeof(item.shipping)!==未定义,但它不起作用。 请帮帮我! 谢谢 – AdminDev826

+0

我从来没有使用过Angular.js,但很快查看文档,似乎可以使用相当复杂的条件。我非常疲倦,所以我不会发布答案,但请检查https://angular.io/docs/ts/latest/guide/structural-directives.html#!#-lt-ng-container-gt-to-提示的救援。 –

回答

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> 
+0

谢谢@Tiep Phan '

  • 运费是{{item.shipping}}
  • ' 它正在为我工​​作! – AdminDev826

    相关问题