Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: formGroup expects a FormGroup instance. Please pass one in. Reactive forms Angular

I am using reactive forms in Angular version 10. But getting the following error.

ERROR Error: formGroup expects a FormGroup instance. Please pass one in.

       Example:

       
    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });
    at Function.missingFormException (forms.js:1700:1)
    at FormGroupDirective._checkFormPresent (forms.js:5632:1)
    at FormGroupDirective.ngOnChanges (forms.js:5454:1)
    at FormGroupDirective.rememberChangeHistoryAndInvokeOnChangesHook (core.js:2373:1)
    at callHook (core.js:3285:1)
    at callHooks (core.js:3251:1)
    at executeInitAndCheckHooks (core.js:3203:1)
    at selectIndexInternal (core.js:6324:1)
    at ɵɵadvance (core.js:6306:1)
    at PatientInformationComponent_Template (template.html:39:34)

My sample HTML code is as follows.

<div [formGroup]="MyForm">
      <input formControlName="firstName">
      <input formControlName="lastName">
</div>

My TS code:

export class MyComponent implements OnInit{
   MyForm: FormGroup;

   constructor( private formbuilder: FormBuilder) {}

   ngOnInit() {
       this.MyForm= this.formbuilder.group({
        firstName: new FormControl("", Validators.maxLength(100)),
        lastName: new FormControl("",Validators.maxLength(100)),
    });
   }

}

Although the form works properly, but the error always shows in the console. I think it might be because of some other lifecycle hook. Could you give me some solution for this.

like image 227
Nitish Thorat Avatar asked Jul 18 '26 06:07

Nitish Thorat


1 Answers

Since you haven't initialized your form called myForm in .ts code, you should try adding *ngIf and change div HTML tag to form element.

<form *ngIf="form" 
     [formGroup]="MyForm">
        <input formControlName="firstName">
        <input formControlName="lastName">
</form>
like image 116
Chaka15 Avatar answered Jul 19 '26 20:07

Chaka15



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!