加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

变量 – Angular2 – 如果不检查是否存在{{object.field}}错误

发布时间:2020-12-17 08:08:07 所属栏目:安全 来源:网络整理
导读:我有一个关于检查对象中某些字段是否存在的问题。我想打印所有类别的用户拥有,所以我在做这样的事情: ul *ngIf="user.categories.length 0" *ngFor="#category of user.categories" li {{category.name}} /li /ul 原因?所有数据均已正确打印,但我在Web控
我有一个关于检查对象中某些字段是否存在的问题。我想打印所有类别的用户拥有,所以我在做这样的事情:
<ul *ngIf="user.categories.length >  0" *ngFor="#category of user.categories">
    <li>
      {{category.name}}
    </li>
  </ul>

原因?所有数据均已正确打印,但我在Web控制台中收到错误,如:

Cannot read property 'name' of null

但是当我做这样的事情:

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

那么一切都没关系我做错事,也许每次都要检查一下吗?你有没有像这样的问题?提前致谢。

基本用法

使用安全导航操作符

{{category?.name}}

那么当类别不为空时,只读取名称。

排列

这只适用于。 (de引用)运算符。
对于可以使用的数组

{{records && records[0]}}

参见Angular 2 – Cannot read property ‘0’ of undefined error with context ERROR CONTEXT: [object Object]

异步管道

使用异步管道可以像

{{(chapters | async)?.length

ngModel

使用ngModel目前需要将其拆分

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

参见Data is not appending to template in angular2

* ngIf

一个替代方法是使用* ngIf =“data”来封装视图的一部分,以防止在数据可用之前部分被渲染以防止取消引用错误。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读