angular - 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],
})
}
这里在userProfile
and phone_number
childphone_number
并且isd_code
最初不可用。因此,当我尝试编辑个人资料页面时,我收到了错误
错误类型错误:无法在 profileEditComponent.ngOnInit 处读取 null 的属性“isd_code”
在 html 中,我使用安全导航运算符,但在这里我必须设置值,formbuilder
否则即使设置了值,验证也会失败。
我试图检查该属性是否未定义,但它不起作用this.userProfile.phone_number.isd_code != undefined
。
解决方案
对打字稿使用安全导航运算符?
或三元运算符
试试这样:
this.userProfile?.phone_number?.isd_code != undefined
在 TS 中:
isd_code: [(this.userProfile)?(this.userProfile.phone_number ? this.userProfile.phone_number.isd_code : null) : null],
推荐阅读
- ruby - Ruby 循环覆盖值
- javascript - 查找两点之间的相对角度
- matlab - MATLAB中的大量线性方程
- python - 无法使用 Python Selenium 启动 Opera
- javascript - MongoDB 聚合管道以获取每个不同状态的员工数量
- python - 每次都给出字典顺序更大的字符串的自由函数
- r - 导入和转换许多 csv 文件
- go - 每个 HTTP 请求都应该有一个新的 datastore.Client 吗?
- valgrind - FreeBSD 上 valgrind 的限制
- swift - 硬编码 NSUserActivityTypes 以恢复不同的数据模型