NgFor/NgIf中的Angular 2对象插值问题

Angular 2 Object Interpolation Issue in NgFor/NgIf

本文关键字:对象 插值 问题 Angular NgIf 中的 NgFor      更新时间:2023-09-26

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

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

现在,如果对象层次结构中没有user.fbdetails,则包装<img>的div不应该显示。这适用于几乎所有的用户(大多数没有详细信息)。这意味着没有填充绑定{{user.fbdetails.picture.data.url}}的内插值,但是如果没有fbdetails, *ngIf应该阻止这些绑定存在。然而,我仍然得到一个Cannot read property "picture" of undefined错误,即使这应该永远不会发挥作用,因为*ngIf

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

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

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

这样,如果fbdetailsnull, Angular就不会抛出异常。

获取错误
  <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读取图片