2016-08-18 50 views
0

对于一组User对象,我有一个*ngFor。在此ngFor内部是一个带有*ngIf的div,并且在该div内部是具有插值src属性的<img>标签。NgFor中的角度2对象插值问题/ NgIf

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

现在包装了<img>如果有对象层次没有user.fbdetails不应显示DIV。这适用于几乎所有有问题的用户(大多数没有fbdetails)。这意味着绑定{{user.fbdetails.picture.data.url}}的内插值未被填充,但*ngIf应阻止这些绑定存在,如果没有fbdetails。然而,我仍然得到一个Cannot read property "picture" of undefined的错误,尽管由于*ngIf而不应该发挥作用。

这是我在Angular 1中经常做的事情,所以我不确定发生了什么。

回答

1

使用安全导航操作画面应该解决您的问题

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

这如果fbdetailsnull,角度不会丢。

+0

甚至不知道这存在。这是角度2还是打字稿?这个是从哪里来的? –

+0

它是Angular2模板语法。 AFAIK它被认为是增加到ES6但尚未降落。 –

0

错误,你得到是

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

它试图读取user.fbdetails