cnak2
cnak2

Reputation: 1841

Can't display target array within object using *ngFor

I have an angular app where for one view I'm displaying a list of contact phone numbers.

Example of my object:

contact: { name:'sam smith', phones:[ {phone_type:'home', phone_number:'222-222-2222'}, {phone_type:'mobile', phone_number:'333-333-3333'} ] }

In my html I can access the contact name with {{contact.name}}

But if I try to loop the phones array with *ngFor like this:

<div *ngFor="let phone of contact.phones">{{phone.phone_number}}</div>

I get:

"ContactEditPage.html:61 ERROR TypeError: Cannot read property 'phones' of undefined".

So I know the object is being returned, but why can't I look through the phones array?

Upvotes: 0

Views: 203

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222720

You should use safe navigation operator to check if the values are there because your api call return the data asynchronously

<div *ngFor="let phone of contact?.phones">{{phone?.phone_number}}</div>

Upvotes: 2

Related Questions