Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formGroup expects a FormGroup instance. Please pass one in

THE SITUATION:

I am trying to make a very simple login form in my Ionic 2 app.

No matter what I try, I keep getting this error:

formGroup expects a FormGroup instance. Please pass one in.

formGroup expects a FormGroup instance. Please pass one in.

THE CODE:

The page component:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FormGroup, Validators, FormBuilder }  from '@angular/forms';

@Component({
  selector: 'login-page',
  templateUrl: 'login-page.html'
})

export class LoginPage {

    loginForm: FormGroup;

    constructor(public navCtrl: NavController, private formBuilder: FormBuilder) {}

    ionViewDidLoad() 
    {
        console.log('Login page loaded');

        this.loginForm = this.formBuilder.group({
            email: ['', Validators.required],
            password: ['', Validators.required],
        });
    }

    submitLogin() 
    {
        console.log('Doing login..');
    }

}

The view:

<ion-header>
  <ion-navbar>
    <ion-title>LoginPage</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

    <form [formGroup]="loginForm" (ngSubmit)="submitLogin()">

    <ion-item>
        <ion-label>Email</ion-label>
        <ion-input #email type="email" formControlName="email"></ion-input>
    </ion-item>

    <ion-item>
        <ion-label>Password</ion-label>
        <ion-input #password type="text" formControlName="password"></ion-input>
    </ion-item>

    <button ion-button block type="submit">Submit</button>

    </form>

</ion-content>

THE QUESTION:

Do you why am I getting the error?

Do you know what is wrong with that code?

Thanks!

like image 239
FrancescoMussi Avatar asked Nov 17 '16 12:11

FrancescoMussi


2 Answers

Add the code in the ionViewDidLoad into the constructor. It's probably not assigning the form in time, causing the view to use undefined

like image 192
Paul Samsotha Avatar answered Sep 22 '22 17:09

Paul Samsotha


The formBuilder init was ngOnInit method. That must be in the constructor.

like image 39
Alejandro Avatar answered Sep 26 '22 17:09

Alejandro