2017-05-06 38 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

    相關問題