Getting an error: formGroup expects a FormGroup instance. Please pass one in

无人久伴 提交于 2020-01-25 06:54:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!