【发布时间】:2018-03-22 20:11:58
【问题描述】:
如何在 Angular 的响应式表单中正确使用 formGroupName?
我无法在我的表单上填充从 Firebase 返回的数据。
您正确地将数据保存在 CloudFirestore 中,为地址创建了一个数组,其中包含值。
目前我正在做以下事情:
myform.model.ts:
export class People {
name: string;
city: string;
postal_code: string;
constructor(data?) {
data = data || {}; // added this line
// before executing the subscribe is coming undefined
// and when I try to access data.adress.postal_code
// there is an error saying that postal_code is undefined
// is passing here twice, the first time comes undefined
console.log (data.adress.postal_code); // undefined
this.name = data.name || '';
this.city = data.adress.city || '';
this.postal_code = data.adress.postal_code || '';
}
}
myform.component.ts:
pageType: string;
people = new People();
onFormChanged: Subscription;
form: FormGroup;
ngOnInit() {
// Subscribe to update form on changes
this.onFormChanged =
this.formService.onFormChanged
.subscribe(data => {
// firebase return
if (data) {
this.people= new People(data);
this.pageType = 'edit';
}
else {
this.pageType = 'add';
this.people = new People();
}
this.form = this.createForm();
});
}
createForm() {
return this.formBuilder.group({
name: [this.people.name, Validators.required],
adress: this.formBuilder.group({
postal_code: [this.people.postal_code],
city: [this.people.city],
}),
});
}
myform.component.html:
<form name="form" [formGroup]="form">
<div fxLayout="row" fxLayout.xs="column" fxLayoutAlign="start">
<mat-form-field fxFlex="20">
<input matInput name="name" placeholder="Name" formControlName="name" required>
</mat-form-field>
</div>
<div fxLayout="row" fxLayout.xs="column" fxLayoutAlign="start">
<mat-form-field fxFlex="20" formGroupName="adress">
<input matInput name="city" placeholder="City" formControlName="city">
</mat-form-field>
<mat-form-field fxFlex="20" formGroupName="adress">
<input matInput name="postal_code" placeholder="Postal code" formControlName="postal_code">
</mat-form-field>
</div>
</form>
从firebase返回的数据是:
{name: 'Person 1', adress: {city: 'City 1', postal_code: '2348917'}}
只需填写姓名...城市和邮政编码未填写,我做错了什么?
【问题讨论】:
标签: angular forms firebase angular-forms