【发布时间】:2020-01-08 21:57:18
【问题描述】:
我想选择存储在我的数据库中的选项字段。
<mat-form-field>
<mat-select [(value)]="this.entities.gender" #gender formControlName="gender">
<mat-option value="f">Female</mat-option>
<mat-option value="m">Male</mat-option>
</mat-select>
</mat-form-field>
private entities: IprofileData;
async ngOnInit() {
this.entities = await this.profileService.getEntities().pipe(take(1)).toPromise();
console.log(this.entities); // <-- This returns all the data that I need
}
但我得到了错误:
ERROR TypeError: Cannot read property 'gender' of undefined
为什么我无法使用this.entities?
更新
我也尝试过使用 FormGroup 设置默认值
private profileFormGroup = this.fb.group({
gender: this.entities.gender
});
但我得到了错误
错误:未捕获(承诺中):TypeError:无法读取未定义的属性“性别”
【问题讨论】:
-
你试过安全导航算子吗?像这样:
this.entities?.gender. -
@R.Richards 如果我这样做,我会收到错误 '?.'运算符不能在赋值中使用
-
试试
entities.gender没有this。 -
@R.Richards 我做了,但我仍然收到错误 Cannot read property 'gender' of undefined
-
您是否在应用程序中使用reactive forms?如果是这样,则需要在表单组中设置默认值。
标签: angular typescript