我是angular的初学者,我正在尝试使用代码构建表单验证我的要求是当我点击 reset 按钮域需要重置为此我遵循了下面的代码但问题是当我点击Reset按钮时我在exception下面可以有人帮我吗我在哪里做了mi-stack
home.html:
<ion-content padding>
<h1>Authentication Demo</h1>
<hr align="left" width="30%">
<form [formGroup]="authForm">
<ion-item>
<ion-label floating>Username</ion-label>
<ion-input type="text" [(ngModel)] ="username" value="" [formControl]="authForm.controls['username']" [ngClass]="{'error-border':!authForm.controls['username'].valid}"></ion-input>
</ion-item><br/>
<div class="error-box" *ngIf="authForm.controls['username'].hasError('required') && authForm.controls['username'].touched">* Username is required!</div>
<ion-item>
<ion-label floating>Password</ion-label>
<ion-input type="password" [(ngModel)] ="password" value="" [formControl]="authForm.controls['password']"></ion-input>
</ion-item><br/>
<div class="error-box" *ngIf="authForm.controls['password'].hasError('required') && authForm.controls['password'].touched">* Username is required!</div>
<div class="error-box" *ngIf="authForm.controls['password'].hasError('minlength') && authForm.controls['password'].touched">* Minimum username length is 8!</div>
<div class="error-box" *ngIf="authForm.controls['password'].hasError('checkFirstCharacterValidatorOutput') && authForm.controls['password'].touched">* Password cant't start with number!</div><br/>
<ion-list>
<ion-item>
<ion-label>Gender</ion-label>
<ion-select [formControl]="authForm.controls['gender']">
<ion-option value="e">Other</ion-option>
<ion-option value="f">Female</ion-option>
<ion-option value="m">Mele</ion-option>
</ion-select>
</ion-item>
</ion-list><br/>
<button type="submit" ion-button full [disabled]="!authForm.valid" (click)="myFunc1()">Submit</button>
<button type="submit" ion-button full [disabled]="!authForm.valid" (click)="myFunc2()">Reset</button>
</form>
</ion-content>
home.ts:
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {FormBuilder, FormGroup, Validators, AbstractControl} from '@angular/forms';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
username:string;
password:string;
authForm : FormGroup;
constructor(public navCtrl: NavController, public navParams: NavParams, private fb: FormBuilder) {
this.authForm = fb.group({
'username' : [null, Validators.compose([Validators.required])],
'password': [null, Validators.compose([Validators.required, Validators.minLength(8)])],
'gender' : 'e'
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad');
}
myFunc1(){
console.log('Form submitted!')
}
myFunc2(){
this.username='';
this.password='';
}
}
例外:
ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。上一个值:'error-border: false‘。当前值:'error-border: true‘。
发布于 2018-05-28 18:52:36
在重置函数myFunc2
中,使用内置的表单重置功能:
myFunc2() {
this.authForm.reset();
}
(顺便说一句,您可能还想重命名该函数...)
https://stackoverflow.com/questions/50564540
复制相似问题