【发布时间】:2021-07-24 10:41:33
【问题描述】:
我正在尝试在 angular 11 中嵌套表单数组。到目前为止,我已经尝试过这样的操作,并且工作正常。
spinner: boolean = false;
new_created: boolean = true;
create_question_form: FormGroup;
group: any = new FormGroup({
name: new FormControl(''),
});
constructor(private route: ActivatedRoute, private fb: FormBuilder) {}
validation() {
this.create_question_form = this.fb.group({
question: new FormArray([this.group]),
});
}
get question() {
return this.create_question_form.get('question') as FormArray;
}
add_question() {
this.question.push(this.group);
}
create_question() {
const data = this.create_question_form.getRawValue();
console.log(data);
}
ngOnInit(): void {
this.validation();
this.add_question();
}
<form
[formGroup]="create_question_form"
(ngSubmit)="create_question()"
>
<ng-container formArrayName="question">
<div *ngFor="let _ of question.controls; index as i">
<ng-container [formGroupName]="i">
<div class="col-12 col-md-4 mt-5">
<span class="p-float-label w-100">
<input
type="text"
id="inputtext"
class="form-control"
formControlName="name"
pInputText
/>
<label for="inputtext">Name</label>
</span>
</div>
</ng-container>
</div>
</ng-container>
<button type="submit" class="btn btn-success">Create</button>
</form>
但我想要的是在我的 Formgroup 中创建一个新的 FormArray (Address),如下所示。
group: any = new FormGroup({
name: new FormControl(''),
address:new FormArray([]),
});
我不知道如何在我的 HTML 中访问这个 address 表单数组,或者如何在这个数组中推送新的 FormControl。
【问题讨论】:
-
这能回答你的问题吗:stackoverflow.com/questions/68433975/…
-
如果它不适合您,您可以创建 stackblitz 链接。
-
它对我不起作用。我的表单不同 formgroup>formarray>formgroup>formarray
-
stackblitiz : stackblitz.com/edit/…
标签: angular typescript angular-reactive-forms