. Advertisement .
..3..
. Advertisement .
..4..
I am new to Angular 2 and unable to resolve this issue ”formgroup expects a formgroup instance please pass one in”.
I’m only beginning to understand about angular reactive forms, and I want to try the first example but I’m having trouble.
This 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 here 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);
}
}
I can see the Username and Email fields in the output, but not the Gender field.
I appreciate any help from you.
The cause: This error happens because you forgot creating an instance for the FormGroup defined in your template which is
signupForm
Solution: To fix the error, you have to create an instance for
signupForm
like the following: