角度错误TypeError:无法读取null的属性“ isd_code”

时间:2019-09-16 08:22:58

标签: angular formbuilder

Component.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],
})
}

userProfile中,phone_number和子phone_numberisd_code最初不可用。因此,当我尝试编辑个人资料页面时,出现错误

  

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

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

我试图检查属性是否未定义,但this.userProfile.phone_number.isd_code != undefined无效。

3 个答案:

答案 0 :(得分:1)

对打字稿使用安全的导航操作符 ? 或三元操作符

尝试这样:

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

在TS中:

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

答案 1 :(得分:1)

这种情况下的问题可能是this.userProfile.phone_number的值为 null ,而您正在尝试访问值为 null 的元素的属性。 。 尝试访问属性之前,应检查this.userProfile.phone_number的值:

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 ? this.userProfile.phone_number.isd_code : ''],
            phone_number: [this.userProfile.phone_number ? this.userProfile.phone_number.phone_number : '']
})

答案 2 :(得分:0)

为什么不使用空对象对其进行初始化。

@Input() userProfile: any= new UserProfile();

然后在UserProfile中确保您已使用空对象将phone_number初始化。

相关问题