尝试使用 [(value)] 属性时出错
2020-01-08
130
我想选择存储在数据库中的选项字段。
<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
});
但是我得到了错误
Error: Uncaught (in promise): TypeError: Cannot read property 'gender' of undefined
2个回答
不要将
value
与
formControlName
一起使用,而应使用
formControlName
template
<mat-form-field>
<mat-select #gender formControlName="gender">
<mat-option value="f">Female</mat-option>
<mat-option value="m">Male</mat-option>
</mat-select>
</mat-form-field>
component.ts
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
// you need to put the value into formGroup
this.profileFormGroup.get('gender').patchValue(this.entities.gender);
}
Ashot Aleqsanyan
2020-01-09
首先,您不能在模板中使用
this
其次,您不能在模板中使用
private
属性,它们必须是公共的。
第三,我建议您坚持使用可观察对象而不是承诺,这是一个更好的解决方案
<mat-form-field>
<mat-select [(value)]="entities$ | async as entities" #gender
formControlName="entities?.gender">
<mat-option value="f">Female</mat-option>
<mat-option value="m">Male</mat-option>
</mat-select>
</mat-form-field>
entities$: Observable<IprofileData>;
ngOnInit() {
this.entities$ = this.profileService.getEntities().pipe(take(1));
}
Murhaf Sousli
2020-01-09