我试图在另一个 FormArray
中添加一个 FormArray
但不知道如何去做。
我的 typescript 文件中有这个:
createForm() {
this.myForm = this.formBuilder.group({
people: this.formBuilder.array([
{ addresses: this.formBuilder.array([]) }
])
});
}
基本上,我想说的是创建一个 people
FormArray
,其中每个人都可以有多个地址。我尝试在我的 html 中像这样呈现它:<div [formGroup]="myForm">
<div formArrayName="people">
<div *ngFor="let person of people.controls; let i=index">
Person {{ i + 1 }}
<div *ngFor="let address of person.addresses.controls; let j=index">
Address {{ j + 1 }}
</div>
</div>
</div>
</div>
当然,这只是一个例子,我的实际表格会有更多的进展。我有一个“添加人员”链接,它在我的 typescript 中调用一个函数,该函数将一个对象推送给人们
FormArray
。当我调用
createForm()
时,我在浏览器中收到以下错误:ERROR TypeError: this.form._updateTreeValidity is not a function
ERROR TypeError: this.form.get is not a function
我究竟做错了什么?我如何完成我想做的事?任何帮助,将不胜感激!
最佳答案
尝试这样的事情:
stackblitz example
HTML:
<form [formGroup]="myForm" (ngSubmit)="submit()">
<div formArrayName="people">
<div *ngFor="let person of getPeople(myForm); let i=index">
<div style="margin: 5px;" [formGroupName]="i">
<label>Person {{ i + 1 }}</label>
<input type="text" placeholder="Name" formControlName="name">
<button *ngIf="i<1" (click)="addPeople()" type="button">Add People</button>
<div formArrayName="addresses">
<div *ngFor="let address of getAddress(person); let j=index">
<div [formGroupName]="j">
<span>Address {{ j + 1 }}</span>
<input type="text" placeholder="house No" formControlName="houseNo">
<input type="text" placeholder="city" formControlName="city">
<button *ngIf="j<1" (click)="addAddress(i)" type="button">+</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div style="margin-top: 20px;">
{{myForm.value | json}}
</div>
TS:
import { Component, OnInit } from '@angular/core';
import { FormArray, FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
survey: FormGroup;
myForm: FormGroup;
constructor(private fb: FormBuilder) {
}
ngOnInit() {
this.createForm();
}
createForm() {
this.myForm = this.fb.group({
people: this.fb.array([this.createPeopleArray()])
})
}
createPeopleArray() {
return this.fb.group({
name: null,
addresses: new FormArray([
this.createAddressArray()
])
});
}
getPeople(form) {
return form.controls.people.controls;
}
getAddress(form) {
return form.controls.addresses.controls;
}
createAddressArray() {
return this.fb.group({
houseNo: null,
city: null
})
}
addPeople() {
const control = <FormArray>this.myForm.get('people');
control.push(this.createPeopleArray());
}
addAddress(i) {
const control = <FormArray>this.myForm.get('people').controls[i].get('addresses');
// console.log(control);
control.push(this.createAddressArray());
}
submit() {
console.log(this.myForm.value)
}
}
关于Angular5 响应式表单 : Form array inside another form array,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51435141/