1

In AngularJS, when I wanted to display an specific element from an array, within my view, I would simply reference it like this:

<span>{{contact.emails[0].email_address}}</span>

But for some reason, with the same setup in Angular, I get the error:

Runtime Error
Cannot read property 'email_address' of undefined

So if I return an object of contact that contains an emails array, how do I reference the first item on the array?

2
  • try it with the ? operator, may be for the first time the template is rendered, the array is still undefined. Like, {{ contact?.emails[0]?.email_address }} Commented Nov 8, 2017 at 14:42
  • DV for lack of research, there are at least 3 dups of this question Commented Nov 8, 2017 at 14:48

3 Answers 3

3

Try this:

<span>{{contact.emails[0]?.email_address}}</span>

This is most likely because your emails array is being async loaded, so it is null till your service returns. Using ? makes so it won't try to access the 'email_address' property till its defined, thus not throwing an error at load.

Sign up to request clarification or add additional context in comments.

2 Comments

wdanda, that worked! Thanks for the explanation.
Glad to help :)
0

Maybe you should try to do a

console.log(contact.emails[0])

Because this error means the first item of your array doesn't exist.

Otherwise, if it existed, it would work like that !

<span>{{contact.emails[0].email_address}}</span>

Comments

0

Try this: 
<ng-template [ngIf]='contact.emails && contact.emails.length > 0'>
  <span>{{contact.emails[0].email_address}}</span>
</ng-template>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.