问题描述
我有一个关于检查对象中是否存在某些字段的问题.
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>
原因?所有数据均已正确打印,但是在Web控制台中出现如下错误:
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}}
然后,仅当category
不是null
时读取name
.
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]}}
另请参见
异步管道
通过async
管道可以像
{{(chapters | async)?.length
ngModel
ngModel
当前使用ngModel
,需要将其拆分为
With ngModel
currently it needs to be split into
[ngModel]="details?.firstname" (ngModelChange)="details.firstname = $event"
另请参见数据未附加到angular2
*ngIf
*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}}是否存在则出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!