组件中可访问变量,但模板中未定义

时间:2019-09-01 00:40:34

标签: angular typescript

在尝试使用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>

1 个答案:

答案 0 :(得分:2)

  

无法读取未定义的属性

此错误是由于呈现视图的clearanceInfo属性仍然为undefined,并且您试图访问该undefined值的属性而引起的。

如果值为?null,则可以使用Angular的safe navigation operator undefined来防止视图渲染失败。

*ngIf='clearanceInfo?.dad == 0'

添加?运算符将解决该错误。