NgFor / NgIf

时间:2016-08-18 23:16:36

标签: javascript angular

我有一个用户对象数组的*ngFor。在此ngFor内部是一个带有*ngIf的div,在此div中,是一个带有插值<img>属性的src标记。

<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中经常做的事情,所以我不确定发生了什么。

2 个答案:

答案 0 :(得分:1)

使用安全导航操作符可以解决您的问题

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

如果fbdetailsnull,Angular就不会抛出。

答案 1 :(得分: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中读取图片

相关问题