本文介绍了formGroup 需要一个 FormGroup 实例.请传入一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:

我正在尝试在我的 Ionic 2 应用中制作一个非常简单的登录表单.

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.

代码:

页面组件:

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..');
    }

}

观点:

<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>

问题:

你为什么会收到错误消息?

Do you why am I getting the error?

你知道那段代码有什么问题吗?

Do you know what is wrong with that code?

谢谢!

推荐答案

ionViewDidLoad中的代码添加到构造函数中.可能是没有及时分配表单,导致视图使用 undefined

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

这篇关于formGroup 需要一个 FormGroup 实例.请传入一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 15:51