Angular form group: cannot find control with unspecified name attribute

Viewed 2241

I'm having a problem with my Angular app. I'm trying to create 3 forms. Here is my template:

<div *ngFor="let item of formNames; index as i" >
    {{formNames[i]}}
<form [formGroup]='formFields[i]'>      
  <label>          
      Name:
     <input type="text" [formControl]="formFields[i].name">
  </label>      
   <label>
  All:
  <input type="text" [formControl]="formFields[i].all">      
</label>
<label>
   Done:
  <input type="text" [formControl]="formFields[i].done">      
</label>
<label>
  Ctrl:
  <input type="text" [formControl]="formFields[i].ctrl">      
</label>
<label>
  Rjct:
  <input type="text" [formControl]="formFields[i].rjct">      
</label>
</form>
</div>

The problem is that when the page loads, it renders only the first {{formnames[i]}}. Console says "ERROR Error: Cannot find control with unspecified name attribute".

Here is the code I use to render FormGroups:

export class TableDataFormComponent {
  formFields: Array<any> = fields;
  formNames = FORMINPUTS;
  say = f; 
}

let f = function() {console.log(this.formFields); };

const FORMINPUTS: Array<string> = [];

TableHeaders.HEADERS.forEach((item) => {
  FORMINPUTS.push(item);
});

let fields: Array<FormGroup> = [];

for (let i = 0; i < FORMINPUTS.length; i++) {
    fields[i] = new FormGroup({
    name: new FormControl(''),
    all: new FormControl(''),
    done: new FormControl(''),
    ctrl: new FormControl(''),
    rjct: new FormControl('')
  });
}

Here is the video of the problem: https://yadi.sk/i/4GnZpJLV38oWMg

Stackblitz for some reason is not working for my project, but the source code is here: https://stackblitz.com/github/kulaska/Table-app/tree/adding_forms_branch

I don't understand why data renders after interacting with buttons or input elements. It somehow triggers creating of new FormGroup. Obviously, I need all of them to be created at the same time, without interacting with DOM. Has anyone had the same issue? What do I do to solve this? I'd really appreciate your help

1 Answers

Your best bet is to use the FormBuilder.

this.formBuilder.array([ this.createItem() ])

createItem(): FormGroup {
  return this.formBuilder.group({
    name: '',
    all: '',
    done: '',
    ...
  });
}

And your template will need to use
formArrayName="fields" and [formGroupName]="i"

See this article for more details:
https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/

Related