我无法在我的表单上填充从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'}}
只需填写姓名......城市和邮政编码没有填写,我做错了什么?
答案 0 :(得分:0)
您只需要使用formGroupName
一次:
<div fxLayout="row" fxLayout.xs="column" fxLayoutAlign="start" formGroupName="adress">
<mat-form-field fxFlex="20" >
<input matInput name="city" placeholder="City" formControlName="city">
</mat-form-field>
<mat-form-field fxFlex="20">
<input matInput name="postal_code" placeholder="Postal code" formControlName="postal_code">
</mat-form-field>
</div>
在您的模型构造函数中,您需要访问adress
属性才能访问city
或postal_code
:
constructor(data?) {
this.name = dataname || '';
this.city = data.adress.city || '';
this.postal_code = data.adress.postal_code || '';
}