问题描述
我有一个关于检查对象中的某个字段是否存在的问题.
I have a question about checking if some field in object exists.
我想打印用户拥有的所有类别,所以我正在做这样的事情:
I want to print all categories which user has so I'm doing something like this:
<ul *ngIf="user.categories.length > 0" *ngFor="#category of user.categories">
<li>
{{category.name}}
</li>
</ul>
原因?所有数据都正确打印,但我在网络控制台中收到如下错误:
The reason? All the data are PROPERLY printed, but I'm getting an error in web console like this:
Cannot read property 'name' of null
但是当我做这样的事情时:
But when I do something like:
<ul *ngIf="user.categories.length > 0" *ngFor="#category of user.categories">
<li *ngIf="category">
{{category.name}}
</li>
</ul>
然后一切都好.
我是不是做错了什么,还是我每次都得检查?你遇到过这样的问题吗?
Am I doing something wrong or maybe I have to check this every time? Have you ever had a problem like this one?
推荐答案
基本用法
使用安全导航操作符
{{category?.name}}
then name
仅在 category
不是 null
时才被读取.
then name
is only read when category
is not null
.
数组
这仅适用于 .
(取消引用)运算符.对于数组,您可以使用
This only works for the .
(dereference) operator.For an array you can use
{{records && records[0]}}
另见 Angular 2 - 无法使用上下文错误上下文读取未定义错误的属性0":[object Object]
异步管道
使用 async
管道,它可以像
With async
pipe it can be used like
{{(chapters | async)?.length
ngModel
使用 ngModel
目前需要拆分为
With ngModel
currently it needs to be split into
[ngModel]="details?.firstname" (ngModelChange)="details.firstname = $event"
*ngIf
另一种方法是始终使用 *ngIf="data"
包装视图的一部分,以防止在 data
可用之前完全渲染该部分以防止取消引用错误.
An alternative is always to wrap the part of the view with *ngIf="data"
to prevent the part being rendered at all before the data
is available to prevent the dereference error.
这篇关于如果不检查 {{object.field}} 是否存在则出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!