Thi*_*ibs 8 angular angular-forms
我正在构建一个 CRUD 应用程序 Angular 6.
我的表单用于添加和更新项目。当用户更新项目时,表单会从服务器预先填充。当服务器更新表单时,它会触发验证。
如何在不触发验证的情况下更新表单值?
这是相关的代码:
ngOnInit(){
this.form = this.fb.group({
name: ['', [Validators.required], MyAsyncValidator],
comments: [''],
});
this.http.get('/api')
.subscribe((data: any) => {
this.form.setValue({ name: data.name, comments: data.comments });
});
//How to populate form without triggering validation
}
Run Code Online (Sandbox Code Playgroud)
模板:
<form [formGroup]="form">
<div class="form-group row">
<label class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input formControlName="name"
class="form-control"
[ngClass]="{'is-invalid': isInvalid(form.controls.name)}"
type="text">
<small *ngIf="form.get('name').status=='PENDING'" class="form-text text-muted">
<i class="fa fa-spinner fa-spin"></i> Checking Name...
</small>
<small class="invalid-feedback">
<div *ngIf="form.controls['name'].hasError('required')">Name Required</div>
<div *ngIf="form.controls['name'].hasError('exists')">Name Exists</div>
</small>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
小智 7
我认为这要么是角度上的错误,要么是代码中实现的一些奇怪的行为。我也遇到了同样的问题,通过源码调试才发现:
setValue 将调用 updateValueAndValidity():https ://github.com/angular/angular/blob/39c8baea318e740111b1c748718c3203a61b4cdf/packages/forms/src/model.ts#L941
在 updateValueAndValidity() 中,它调用 asyncValidatior: https://github.com/angular/angular/blob/39c8baea318e740111b1c748718c3203a61b4cdf/packages/forms/src/model.ts#L554
我的印象是,设置时emitEvent: false,不应触发任何验证,但事实并非如此。更奇怪的是,无论你设置updateOn为change还是blursetValue 都会触发 asyncValidator。
我别无选择,只能在每次 setValue 调用之前删除 asyncValidator 并在之后将其添加回来。
Pra*_*chi -2
尝试单独更新它们。
this.form.controls.name.setValue(data.name);
this.form.controls.comments.setValue(data.comments);
Run Code Online (Sandbox Code Playgroud)
在 HTML 中使用它作为异步验证器:
<small class="invalid-feedback">
<div *ngIf="form.controls['name'].hasError('required')">Name Required</div>
<div *ngIf="form.controls['name'].touched && form.controls['name'].hasError('exists')">Name Exists</div>
</small>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7871 次 |
| 最近记录: |