在尝试使用ngIf显示表单之前,我正在尝试从数据库中检查值。我console.log
时已获取值并确认它出现在控制台中。但是,当我将其绑定到ngIf指令时,尽管它仍然给出了预期的行为,但它说"cannot read property of undefined"
。
我的组件
ngOnInit() {
let p = {
user: this.userInfo.reg_no,
key: '06'
}
this.data.postMethod(p).subscribe(
data => {
data['code'] != '00' ? this.clearanceInfo = null :
this.clearanceInfo = data['message'][0];
console.log(this.clearanceInfo)
}
);
}
我的模板:
<mat-card *ngIf='clearanceInfo.dad == 0'>
<form>
//*********//
</form>
</mat-card>
答案 0 :(得分:2)
无法读取未定义的属性
此错误是由于呈现视图的clearanceInfo
属性仍然为undefined
,并且您试图访问该undefined
值的属性而引起的。
如果值为?
或null
,则可以使用Angular的safe navigation operator undefined
来防止视图渲染失败。
*ngIf='clearanceInfo?.dad == 0'
添加?
运算符将解决该错误。