Getting Error: formGroup expects a FormGroup instance. Please pass one in
Asked Answered
M

3

12

I am new to Angular 2 and unable to resolve this issue even after going through other stack overflow answers.

I have just now started learning angular reactive forms and want to try the first example but am stuck. Please help.

Here is the HTML form.

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
        <div id="user-data">
          <div class="form-group">
            <label for="username">Username</label>
            <input
              type="text"
              id="username"
              formControlName="username"
              class="form-control">
          </div>
          <div class="form-group">
            <label for="email">Email</label>
            <input
              type="email"
              id="email"
              formControlName="email"
              class="form-control">
          </div>
          <div class="radio" *ngFor="let gender of genders">
            <label>
              <input
                type="radio"
                class="form-control"
                formControlName="gender"
                [value]="gender">{{ gender }}
            </label>
          </div>
        </div>
        <button class="btn btn-primary" type="submit">Submit</button>
      </form>
    </div>
  </div>
</div>

And this is the TS file.

import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  genders = ['male', 'female'];
  // property to hold the form
  sigupForm: FormGroup;

  ngOnInit() {
    // initialize the form before rendering the template
    // hence 'OnInit' because this gets executed before the template is rendered// pass js object
    // {} tells this form doesn't has any 'controls'
    // 'controls' are key-value pairs to the overall form group

    this.sigupForm = new FormGroup({
      // form controls
      // arg1 - intial state/value of this control
      // arg2 - single validator or an array of validators
      // arg3 - async validators
      'username': new FormControl(null),
      'email': new FormControl(null),
      'gender': new FormControl('male')
    });
  }

  onSubmit() {
    console.log(this.sigupForm);
  }
}

In the output, I can see Username and Email Field but no Gender field.

Would you please help me out with fixing this?

I am sure it would be a minor change only but still, I am unable to figure out.

Mateusz answered 2/1, 2018 at 2:19 Comment(1)
maybe it is because of the typo >>> sigupForm instead of signupForm in the .ts-fileHollenbeck
D
10

formGroup expects a FormGroup instance means that you did not create an instance for the FormGroup defined in your template which is signupForm

so you have to create an instance for signupForm like this:

this.signupForm = new FormGroup({
  // form controls
  // arg1 - intial state/value of this control
  // arg2 - single validator or an array of validators
  // arg3 - async validators
  'username': new FormControl(null),
  'email': new FormControl(null),
  'gender': new FormControl('male')
});
Daemon answered 2/1, 2018 at 2:32 Comment(0)
F
15

In my case, I was using Reactive Forms and loading the data for form asynchronously from a service. But, the form template will start getting generated parallelly. And at that time form would be undefined as it would be built only after the data from API call was received. So, first, check if the form is initialized, then only start generating the template.

<form class="col-sm-12 form-content" *ngIf="form" [formGroup]="form">
Fraley answered 20/4, 2019 at 9:19 Comment(2)
Your solution gets rid of the error, but if the asynchronous data is not ready, the form doesn't load. Also, I'm confused because shouldn't the form only load after ngOnInit is complete? Isn't there any way to delay loading of the form until after all the asynchronous data is ready?Eogene
Found that in a situation where using async ngOnInit(). Then *ngIf="form" will fix the issueLily
D
10

formGroup expects a FormGroup instance means that you did not create an instance for the FormGroup defined in your template which is signupForm

so you have to create an instance for signupForm like this:

this.signupForm = new FormGroup({
  // form controls
  // arg1 - intial state/value of this control
  // arg2 - single validator or an array of validators
  // arg3 - async validators
  'username': new FormControl(null),
  'email': new FormControl(null),
  'gender': new FormControl('male')
});
Daemon answered 2/1, 2018 at 2:32 Comment(0)
S
5

Please double check your component code. What I noticed is that the variable you defined there is different to the one specified in your template.

You should change the reference of sigupForm to signupForm instead.

Sulphide answered 2/1, 2018 at 2:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.