angular-materialangular-reactive-formsangular2-formbuilder

How can i fix Error: formControlName must be used with a parent formGroup directive. - Angular ReactiveForms FormBuilder


I'm getting this error:

ERROR Error: formControlName must be used with a parent formGroup directive.  You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class).

I have already import import { ReactiveFormsModule } from '@angular/forms'; in module.ts

this is the template .html:

<mat-step [stepControl]="bankFormGroup" label="Some label">
    <form [formGroup]="bankFormGroup">
        <mat-form-field>
            <mat-label>Banco</mat-label>
            <mat-select ngDefaultControl formControlName="bank">
                <mat-option *ngFor="let bank of banks" value="{{bank.id}}">
                    {{bank.id}} - {{bank.name}}
                </mat-option>
            </mat-select>             
        </mat-form-field>
        <mat-form-field>
            <mat-label>Agência</mat-label>
            <input matInput formControlName="agency" placeholder="0001">                
        </mat-form-field>
        <mat-form-field>
            <mat-label>Número da Conta Corrente</mat-label>
            <input matInput formControlName="account" placeholder="26262661">                
        </mat-form-field>
        {...action form}
    </form>
</mat-step>

this is the component.ts:

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export class UploadComponent {
  
  bankFormGroup: FormGroup = this._formBuilder.group({
    bank: ['', Validators.required],
    agency: ['', Validators.required],
    account: ['', Validators.required]
  });
  banks: any[] = [
    { id: '001', name: 'Banco do Brasil S.A.' },
    { id: '237', name: 'Banco Bradesco S.A.' },
  ];

 constructor(private _formBuilder: FormBuilder) { }

}

I've already see another issues similar in another pages, like https://stackoverflow.com/questions/43305975 . But still i'm not able to remove this issue.

i'm using:

"@angular/forms": "^11.0.0",
"@angular/core": "^11.0.0",
"@angular/material": "^11.0.3",

Solution

  • The error was in another form in same component. Another form without <form [formGroup]="FormGroupName"> parent..

    Check if there is another form without a parent container with [formGroup]