【问题标题】:How to show error message on forms in ionic 2如何在 ionic 2 中的表单上显示错误消息
【发布时间】:2017-01-09 07:57:13
【问题描述】:

以下代码在浏览器中运行良好。

这是我的 .html

 <ion-item>
   <ion-label primary floating>FIRST NAME</ion-label>
   <ion-input type="text" id="firstname" class="form-control" formControlName="firstname"></ion-input>
 </ion-item>

 <p *ngIf="myForm.controls.firstname.errors && myForm.controls.firstname.dirty ">
    <small class="up">
      <strong> <i> Min 3 chars</i></strong>
    </small>
 </p>

这是我的 .ts 文件

this.myForm =  new FormGroup({
            'firstname'      : new FormControl('',[Validators.required,Validators.minLength(3),Validators.maxLength(10)]),
            'lastname'       : new FormControl('', [Validators.required,Validators.minLength(1),Validators.maxLength(10)]),
            'useridphone'    : new FormControl('', [Validators.required,Validators.minLength(10),Validators.maxLength(10)]),
            'password'       : new FormControl('',Validators.compose([Validators.required,Validators.minLength(4),Validators.maxLength(25),
                               Validators.pattern(this.passwordRegex)])),
            'confirmpassword': new FormControl('',Validators.required),
            'email'          : new FormControl( '', Validators.compose([ Validators.required, Validators.pattern(this.emailRegex) ]) )
    })

当我尝试构建我的项目(`ionic build android')时,我在下面遇到错误

类型 '{ [key string]: AbstractControl; 上不存在属性 'firstname' }'。

这是我的ionic info

Cordova CLI: 6.3.0 
Ionic Framework Version: 2.0.0-rc.3
Ionic CLI Version: 2.1.14
Ionic App Lib Version: 2.1.7
Ionic App Scripts Version: 0.0.45
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.4
Node Version: v6.0.0
Xcode version: Not installed

【问题讨论】:

    标签: forms validation angular ionic2


    【解决方案1】:

    您需要通过这种方式访问​​ formControls:

    myForm.controls['firstname']
    

    将您的 p 标签更改为:

    <p *ngIf="myForm.controls['firstname'].errors && myForm.controls['firstname'].dirty ">
    

    【讨论】:

    • 我会使用 myForm.controls['firstname'].touched 这样在用户输入信息并切换到另一个字段之前它不会显示错误消息。
    猜你喜欢
    • 2018-03-03
    • 2015-06-19
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 2012-10-12
    相关资源
    最近更新 更多