[英]How do I make sure a nested form group returns an array of objects in Angular?
我正在 Angular 14 中处理带有嵌套表单组的表单。
在form.component.ts
我有:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css'],
})
export class FormComponent {
public form: FormGroup = new FormGroup({
first_name: new FormControl('', Validators.required),
last_name: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email]),
phone: new FormControl('', Validators.required),
residences: new FormGroup({
city: new FormControl(''),
address: new FormControl(''),
}),
});
constructor() {}
ngOnInit(): void {}
public sendFormData() {
console.log(this.form.value);
}
}
请参阅此处的Stackblitz 。
我需要residences
是一个对象数组。 相反,它本身就是一个 object 。
创建一个表单数组:
public form: FormGroup = new FormGroup({
first_name: new FormControl('', Validators.required),
last_name: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email]),
phone: new FormControl('', Validators.required),
residences: new FormArray([
new FormGroup({
city: new FormControl(''),
address: new FormControl(''),
}),
]),
});
get residencesArray(): FormArray {
return this.form.get('residences') as FormArray;
}
在模板中:
<div
formArrayName="residences"
*ngFor="let residence of residencesArray.controls; let i = index"
>
Residence {{ i + 1 }}
<div [formGroupName]="i">
<mat-form-field appearance="outline" floatLabel="always">
<mat-label class="mat-label">City:</mat-label>
<input class="mat-input" matInput formControlName="city" />
</mat-form-field>
<mat-form-field appearance="outline" floatLabel="always">
<mat-label class="mat-label">Address:</mat-label>
<input class="mat-input" matInput formControlName="address" />
</mat-form-field>
</div>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.