Search code examples
javascriptangulartypescriptangular8angular-forms

formGroup expects a FormGroup instance. Please pass one in when I create a formgroup in other form group


I have this form for addUser and i have field into it for get birthdate .

 this.userFG = this.formBuilder.group({
  name: [""],
  family: [""],
  birthDate: this.formBuilder.group({
    day: [""],
    month: [""],
    year: [""]
  })
});

and I'm using it in the HTML by this :

    <form [formGroup]="userFG">
    <div>
        <label>Name : </label>
        <input formControlName="name">
  </div>
        <div>
            <label>lastName : </label>
            <input formControlName="family">
  </div>
            <div [formGroup]="birthDate">
                <div>
                    <label>day : </label>
                    <input formControlName="day">
  </div>
                    <div>
                        <label>month : </label>
                        <input formControlName="month">
  </div>
                        <div>
                            <label>year : </label>
                            <input formControlName="year">
  </div>
                        </div>
</form>

But when I run the project it shows me this Error :

formGroup expects a FormGroup instance. Please pass one

this is DEMO

Whats the problem? How can I solve it?


Solution

  • Since you are working with a nested form group, for the inner form group use formGroupName:

    <div formGroupName="birthDate">
       ... 
       <input formControlName="day">
       ... 
       <input formControlName="month">
       ...
       <input formControlName="year">
    <div>
    

    Working Stackblitz

    More info about formGroupName can be found in the docs.