2017-05-06 6 views
2

* ngIfを使用して変数が定義されているかどうかを検証する方法はありますか?* ngIfを使用して変数が定義されているかどうかをテストする方法Ionic 2

以下の例では、item.shippingが定義されていてゼロでないため、HTMLには赤いアイテムのみの送料が表示されます。私は青色の項目(出荷は定義されているがゼロ)のコストを表示したいが、緑色の項目(出荷は定義されていない)は表示しない。

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

Iのエラーを表示することができ試した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

    関連する問題