0

I have this code

<div class="photo-gallery1" *ngIf="plans.attachments.length > 0">
...
</div>

and here is json which is plans

enter image description here

and I'm getting error

enter image description here

What can I do? I've tried plans[0].attachments as well but then error is that angular has no idea what 0 is

gsiradze
  • 4,583
  • 15
  • 64
  • 111
  • 2
    Possible duplicate of [Angular2: Cannot read property 'name' of undefined](https://stackoverflow.com/questions/39755336/angular2-cannot-read-property-name-of-undefined) – AT82 May 29 '17 at 12:48
  • Ah.. better dupe, tagged the "wrong one": https://stackoverflow.com/questions/34734671/observable-type-error-cannot-read-property-of-undefined – AT82 May 29 '17 at 12:54

2 Answers2

2

You should use the safe navigation operator (?.) in the template:

*ngIf="plans?.attachments?.length > 0"

Your template is being parsed before the data is loaded. Which means it already tries to evaluate the statement, before plans has been properly set. The safe navigation operator (commonly mistaken for the elvis operator (?:)) is used to prevent null pointers in object parameter navigation

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
0
<div class="photo-gallery1" *ngIf="plans?.attachments?.length > 0">
...
</div>

Replacement of Elvis Operator of Angular2 in Typescript

Yoav Schniederman
  • 5,253
  • 3
  • 28
  • 32