vig*_*age 6 forms validation angular
我在Angular2应用程序中有一个基于模板的表单供用户注册.在那里,我将表单实例传递给Submit函数,并在完成对服务器的异步调用后重置from.
以下是表格中的一些重要部分.
<form class="form-horizontal" #f="ngForm" novalidate (ngSubmit)="onSignUpFormSubmit(f.value, f.valid, newUserCreateForm, $event)" #newUserCreateForm="ngForm">
<div class="form-group">
<label class="control-label col-sm-3" for="first-name">First Name:</label>
<div class="col-sm-9">
<input type="text" class="form-control" placeholder="Your First Name" name="firstName" [(ngModel)]="_userCreateForm.firstName"
#firstName="ngModel" required>
<small [hidden]="firstName.valid || (firstName.pristine && !f.submitted)" class="text-danger">
First Name is required !
</small>
</div>
</div>
.......
.......
<div class="form-group">
<div class="col-sm-offset-3 col-sm-12">
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-link">Reset</button>
</div>
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
在我的组件文件中,我编写了以下函数.
onSignUpFormSubmit(model: UserCreateForm, isValid: boolean, form: FormGroup, event:Event) {
event.preventDefault();
if (isValid) {
this._userEmail = model.email;
this._authService.signUp(this._userCreateForm).subscribe(
res => {
console.log("In component res status = "+res.status);
if(res.status == 201){
//user creation sucess, Go home or Login
console.log("res status = 201");
this._status = 201;
}else if(res.status == 409){
//there is a user for given email. conflict, Try again with a different email or reset password if you cannot remember
this._status = 409;
}else{
//some thing has gone wrong, pls try again
this._serverError = true;
console.log("status code in server error = "+res.status);
}
form.reset();
alert("async call done");
}
);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我提交一个空表单,我会使所有验证工作正常.但是,当我提交有效表单时,一旦表单提交和对服务器的异步调用完成,我就会再次使表单的所有字段无效.
请参阅以下屏幕截图.
我不明白为什么会这样.如果我发表评论form.reset(),我不会得到这个问题.但表单包含我提交的旧数据.
我该如何解决这个问题?
您只需将新模型初始化为表单绑定到的属性并设置submitted = false如下:
public onSignUpFormSubmit() {
...
this.submitted = false;
this._userCreateForm = new UserCreateForm();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3373 次 |
| 最近记录: |