首页 > 解决方案 > Angular ERROR TypeError:无法读取 null 的属性“isd_code”

问题描述

组件.ts

@Input() userProfile: any;
constructor(
    private formBuilder: FormBuilder,
  ) {}
ngOnInit() {
this.profile = this.formBuilder.group({
gender: [this.userProfile.gender],
      first_name: [this.userProfile.first_name, Validators.required],
      last_name: [this.userProfile.last_name, Validators.required],
      isd_code: [this.userProfile.phone_number.isd_code],
      phone_number: [this.userProfile.phone_number.phone_number],
})
}

这里在userProfileand phone_numberchildphone_number并且isd_code最初不可用。因此,当我尝试编辑个人资料页面时,我收到了错误

错误类型错误:无法在 profileEditComponent.ngOnInit 处读取 null 的属性“isd_code”

在 html 中,我使用安全导航运算符,但在这里我必须设置值,formbuilder否则即使设置了值,验证也会失败。

我试图检查该属性是否未定义,但它不起作用this.userProfile.phone_number.isd_code != undefined

标签: angularformbuilder

解决方案


对打字稿使用安全导航运算符?或三元运算符

试试这样:

this.userProfile?.phone_number?.isd_code != undefined

在 TS 中:

isd_code: [(this.userProfile)?(this.userProfile.phone_number ? this.userProfile.phone_number.isd_code : null) : null],

推荐阅读