如果不检查{{object.field}}是否存在则会出错

时间:2016-01-20 21:28:56

标签: variables properties null angular

我有一个关于检查对象中是否存在某个字段的问题。

我想要打印用户拥有的所有类别,以便我这样做:

  <ul *ngIf="user.categories.length >  0" *ngFor="#category of user.categories">
    <li>
      {{category.name}}
    </li>
  </ul>

原因?所有数据都正确打印,但我在网络控制台中收到错误,如下所示:

Cannot read property 'name' of null

但是当我做的事情如下:

  <ul *ngIf="user.categories.length >  0" *ngFor="#category of user.categories">
    <li *ngIf="category">
      {{category.name}}
    </li>
  </ul>

然后一切都好。

我做错了什么或者我每次都要检查一下吗?你有过像这样的问题吗?

1 个答案:

答案 0 :(得分:189)

基本用法

使用安全导航操作员

{{category?.name}}

然后name仅在category不是null时才会被阅读。

<强>阵列

这仅适用于.(取消引用)运算符。 对于数组,您可以使用

{{records && records[0]}}

另见Angular 2 - Cannot read property '0' of undefined error with context ERROR CONTEXT: [object Object]

异步管道

使用async管道,可以像

一样使用
{{(chapters | async)?.length

<强> ngModel

目前,ngModel需要拆分为

[ngModel]="details?.firstname" (ngModelChange)="details.firstname = $event"

另见Data is not appending to template in angular2

<强> *ngIf

另一种方法是始终用*ngIf="data"包裹视图的一部分,以防止在data可用之前完全呈现部分以防止解除引用错误。