为什么表单验证给出此错误错误:ngModel不能用于向父formGroup指令注册表单控件

时间:2017-09-20 05:15:02

标签: angular typescript ionic-framework ionic3

嗨,我得到了这个error

  

错误:ngModel不能用于向父级注册表单控件   formGroup指令

我正在尝试对form inputs

进行基本验证

这是我的form

<form [formGroup]="formgroup">

   <ion-item>
        <ion-label floating>First Name</ion-label>
        <ion-input type="text" formControlName="firstname" [(ngModel)]= "userData.firstname" ></ion-input>
   </ion-item>

   <ion-item *ngIf="firstname.hasError('required') && firstname.touched">
        <p>*First Name Is Required</p>
    </ion-item>

    <ion-item>
        <ion-label floating>Last Name</ion-label>
        <ion-input type="text" formControlName="lastname" [(ngModel)]= "userData.lastname" ></ion-input>
    </ion-item>

   <ion-item *ngIf="lastname.hasError('required') && lastname.touched">
        <p>*First Name Is Required</p>
   </ion-item>  

</form>

这是我的控制器代码

import  {FormBuilder,FormGroup,Validators,AbstractControl,FormControl} from '@angular/forms'; 

    export class Form1Page {

      formgroup:FormGroup;
      firstname:AbstractControl;
      lastname:AbstractControl;

      userData = {"firstname":"", "lastname":""};  

      constructor(public navCtrl: NavController, public navParams: NavParams,public formBuilder:FormBuilder) {

        this.formgroup = formBuilder.group({
                 firstname:['',Validators.required,Validators.minLength(5)],
                 lastname:['',Validators.required,Validators.maxLength(15)]
        });

        this.firstname = this.formgroup.controls['firstname'];

        this.firstname = this.formgroup.controls['lastname'];

        this.userData.dateOfBirth = new Date().toISOString();
      }

}

请帮我摆脱这些error

提前致谢!!!

1 个答案:

答案 0 :(得分:2)

您输错了控件。您有2次分配到firstname,因此您的lastname未初始化。将第二个更改为lastname

替换

 this.firstname = this.formgroup.controls['firstname'];
 this.firstname = this.formgroup.controls['lastname'];

this.firstname = this.formgroup.controls['firstname'];
this.lastname = this.formgroup.controls['lastname'];

Angular Reactive Forms的文档。