0

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?

1
  • It's most likely because you're loading the data asynchronously and you should initialize contact as an object {} Commented Apr 1, 2018 at 3:46

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Does '?' make the call asynchronous?
no it wont throw undefined error until you get the data from the api
That did it. Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.