问题
I am trying to use reactive forms
for dynamic values added on click of button. I am getting below error:
formGroup expects a FormGroup instance. Please pass one in
Here is my example: dynamic-reactive-forms
I am new to reactive forms
. Some code in ts
file:
let numberOfTiles = document.getElementsByClassName("tiledata").length;
if (this.t.length < numberOfTiles) {
for (let i = this.t.length; i < numberOfTiles; i++) {
this.t.push(this.formBuilder.group({
tabName: ['', Validators.required],
dashboardName: ['', Validators.required],
linkTo: ['', Validators.required],
linkSelected: ['', Validators.required]
}));
}
}
get f() { return this.dynamicForm.controls }
get t() { return this.f.alltabs as FormArray; }
onSubmit() {
this.submitted = true;
if (this.dynamicForm.invalid) {
return;
}
alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.dynamicForm.value, null, 4));
}
回答1:
<div [formGroup]="alltabs">
Maybe you forget alltabs
.
回答2:
Try this working StackBlitz
Few things were missing from your code. I have changed your code a bit. Have a look on below code.
<form [formGroup]="dynamicForm" (ngSubmit)="onSubmit()">
<div formArrayName="alltabs">
<div *ngFor="let item of t.controls; index as i" [formGroupName]="i">
Your allTabs
is a FormArray so in HTML you have to define it like a formArray.
Obviously array has iterations so you have to loop through them and find your formGroupName
which is always index, because each form group is on the each index of formArray.
来源:https://stackoverflow.com/questions/59316456/getting-an-error-formgroup-expects-a-formgroup-instance-please-pass-one-in