AdminDev826
AdminDev826

Reputation: 330

How to use *ngIf to test if a variable is defined Ionic 2

Is there a way to use *ngIf to test if a variable is defined, not just if it's truthy?

In the example below, the HTML displays a shipping cost for the red item only, because item.shipping is both defined and nonzero. I'd like to also display a cost for the blue item (shipping defined but zero), but not for the green item (shipping not defined).

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>

it didn't work.

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'shipping' of undefined TypeError: Cannot read property 'shipping' of undefined

Upvotes: 2

Views: 4041

Answers (1)

Tiep Phan
Tiep Phan

Reputation: 12596

you could using something like this

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

or using safe navigation operator

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

Upvotes: 3

Related Questions