P Ackerman P Ackerman - 7 months ago 85
Javascript Question

Angular 2 Object Interpolation Issue in NgFor/NgIf

I have an

for an array of User objects. Inside this
is a div with an
, and inside this div, is an
tag with an interpolated

<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>
<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>

Now the div that wraps the
should not display if there is no
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
is not populated, but the
should prevent those bindings from being present if there are no
. However, I still get a
Cannot read property "picture" of undefined
error, even though that should never come into play because of the

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


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.