[loops] Angular 2 Cannot find control with unspecified name attribute on formArrays

I am trying to iterate over a formArray in my component but I get the following error

Error: Cannot find control with unspecified name attribute

Here is what the logic looks like on my class file

export class AreasFormComponent implements OnInit {
    public initialState: any;
    public areasForm: FormGroup;

    constructor(private fb: FormBuilder) { }

    private area(): any {
      return this.fb.group({
          name: ['', [Validators.required]],
          latLong: ['', [Validators.required]],
          details: ['', [Validators.required]]
      });
    }

    public ngOnInit(): void {
        this.areasForm = this.fb.group({
            name: ['', [Validators.required]],
            areas: this.fb.array([this.area()])
        });
    }
}

and my template file

<form class="areas-form" [formGroup]="areasForm" (ngSubmit)="onSubmit(areasForm.values)">
    <md-input-container class="full-width">
        <input mdInput placeholder="Location Name" type="text" formControlName="name" required>
        <md-error *ngIf="areasForm.get('name').hasError('required')">Please enter the locationName</md-error>
    </md-input-container>
    <md-grid-list cols="1" [formArrayName]="areas">
        <md-grid-tile formGroupName="i"  colspan="1" rowHeight="62px" *ngFor="let area of areasForm.controls.areas.controls; let i = index ">
            <md-grid-list cols="3" rowHeight="60px">
                <md-grid-tile colspan="1">
                    <md-input-container class="full-width">
                        <input mdInput placeholder="Area Name" type="text" formControlName="name" required>
                        <md-error *ngIf="areasForm.get('areas').controls[i].name.hasError('required')">Please enter the area name</md-error>
                    </md-input-container>
                </md-grid-tile>
                <md-grid-tile colspan="1">
                    <md-input-container class="full-width">
                        <input mdInput placeholder="details" type="text" formControlName="details" required>
                        <md-error *ngIf="areasForm.get('areas').controls[i].name.hasError('required')">Please enter the locationName</md-error>
                    </md-input-container>
                </md-grid-tile>
                <md-grid-tile colspan="1">
                    <button md-fab (click)="remove(i)"><md-icon>subtract</md-icon>Remove Area</button>
                </md-grid-tile>
            </md-grid-list>
        </md-grid-tile>
    </md-grid-list>
    <button type="submit" [disabled]="areasForm.invalid" md-raised-button color="primary">Submit</button>
</form>

This question is related to loops angular angular2-forms

The answer is


In my case I solved the issue by putting the name of the formControl in double and sinlge quotes so that it is interpreted as a string:

[formControlName]="'familyName'"

similar to below:

formControlName="familyName"

This was happening for me because I had fromArrayName instead of formArrayName somewhere


Only WinMerge made me find it (by comparison with a version that works). I had a case problem on formGroupName. Brackets around this word can lead to the same problem.


For me, I was trying to add [formGroupName]="i" and/or formControlName and forgetting to specify the parent formArrayName. Pay attention to your form group tree.


The problem for me was that I had

[formControlName]=""

Instead of

formControlName=""

Instead of

formGroupName="i"

You must use:

[formGroupName]="i"

Tips:

Since you're looping over the controls, you've already the variable area, so you can replace this:

*ngIf="areasForm.get('areas').controls[i].name.hasError('required')"

by:

*ngIf="area.hasError('required', 'name')"

So, I had this code:

<div class="dropdown-select-wrapper" *ngIf="contentData">
    <button mat-stroked-button [disableRipple]="true" class="mat-button" (click)="openSelect()" [ngClass]="{'only-icon': !contentData?.buttonText?.length}">
      <i *ngIf="contentData.iconClassInfo" class="dropdown-icon {{contentData.iconClassInfo.name}}"></i>
      <span class="button-text" *ngIf="contentData.buttonText">{{contentData.buttonText}}</span>
    </button>
    <mat-select class="small-dropdown-select" [formControl]="theFormControl" #buttonSelect (selectionChange)="onSelect(buttonSelect.selected)" (click)="$event.stopPropagation();">
      <mat-option *ngFor="let option of options" [ngClass]="{'selected-option': buttonSelect.selected?.value === option[contentData.optionsStructure.valName]}" [disabled]="buttonSelect.selected?.value === option[contentData.optionsStructure.valName] && contentData.optionSelectedWillDisable" [value]="option[contentData.optionsStructure.valName]">
        {{option[contentData.optionsStructure.keyName]}}
      </mat-option>
    </mat-select>
  </div>

Here I was using standalone formControl, and I was getting the error we are talking about, which made no sense for me, since I wasn't working with formgroups or formarrays... it only disappeared when I added the *ngIf to the select it self, so is not being used before it actually exists. That's what solved the issue in my case.

<mat-select class="small-dropdown-select" [formControl]="theFormControl" #buttonSelect (selectionChange)="onSelect(buttonSelect.selected)" (click)="$event.stopPropagation();" *ngIf="theFormControl">
          <mat-option *ngFor="let option of options" [ngClass]="{'selected-option': buttonSelect.selected?.value === option[contentData.optionsStructure.valName]}" [disabled]="buttonSelect.selected?.value === option[contentData.optionsStructure.valName] && contentData.optionSelectedWillDisable" [value]="option[contentData.optionsStructure.valName]">
            {{option[contentData.optionsStructure.keyName]}}
          </mat-option>
        </mat-select>

This happened to me because I left a formControlName empty (formControlName=""). Since I didn't need that extra form control, I deleted it and the error was resolved.


Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to angular2-forms

How can I manually set an Angular form field as invalid? Angular 2 Cannot find control with unspecified name attribute on formArrays Remove all items from a FormArray in Angular Angular ReactiveForms: Producing an array of checkbox values? How to make readonly all inputs in some div in Angular2? tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement" Min / Max Validator in Angular 2 Final TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm" Can't bind to 'formGroup' since it isn't a known property of 'form' ngModel cannot be used to register form controls with a parent formGroup directive