0

I have an *ngFor for an array of User objects. Inside this ngFor is a div with an *ngIf, and inside this div, is an <img> tag with an interpolated src attribute.

<md-card *ngFor="let user of users" [user]="user" style="background-color: rgb(48, 48, 48) !important;">
  <md-card-title-group class="gotham" style="color: rgb(93, 93, 93) !important; font-family: 'Gotham' !important;">

  <md-card-title style="width: 200px !important; text-overflow: ellipsis !important; display: inline-block; overflow: hidden;"><span class="gotham">{{user.username}}</span></md-card-title>
  <md-card-subtitle class="gotham" style="color: rgb(161, 161, 161) !important;"><span class="gotham">User since {{ user.datejoined | date:'fullDate' }}</span></md-card-subtitle>
  <md-list>
  </md-list>
  <div *ngIf="user.fbdetails" style="display: inline-block; float: right;"><img style="width: 40px; height: 40px;" src="app/assets/facebook_circle_color-512.png"/></div>
  <div *ngIf="user.twitterdetails" style="display: inline-block; float: right;"><img style="width: 40px; height: 40px;" src="app/assets/twitter_circle_color-256.png"/></div>
  <i *ngIf="!user.fbdetails.picture.data.url" class="material-icons" style="font-size: 60px; color: white !important; display: inline-block; float: right;">people</i>
  <div *ngIf="user.fbdetails" style="display: inline-block; float: right;"><img style="width: 60px; height: 60px;" src="{{user.fbdetails.picture.data.url}}"/></div>
  </md-card-title-group>
</md-card>

Now the div that wraps the <img> should not display if there is no user.fbdetails in the object hierarchy. This applies to almost all of the users in question (most do not have fbdetails). Which means the interpolated value of the binding {{user.fbdetails.picture.data.url}} is not populated, but the *ngIf should prevent those bindings from being present if there are no fbdetails. However, I still get a Cannot read property "picture" of undefined error, even though that should never come into play because of the *ngIf.

This is something that I did fairly often in Angular 1, so I'm not sure what's going on.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
P Ackerman
  • 2,266
  • 20
  • 24

2 Answers2

1

Using the safe-navigation operator should fix your problem

<i *ngIf="!user.fbdetails?.picture?.data?.url"

This way Angular doesn't throw if fbdetails is null.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

Error that you are getting is from

  <i *ngIf="!user.fbdetails.picture.data.url" class="material-icons" style="font-size: 60px; color: white !important; display: inline-block; float: right;">people</i>

It is trying to read picture from user.fbdetails