我正在使用Angular 6.
构建一个CRUD应用程序
我的表单用于添加和更新项目。当用户更新项目时,表单将从服务器预先填充。当服务器更新表单时,它会触发验证。
如何在不触发验证的情况下更新表单值?
这是相关代码:
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
}
模板:
<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>
我认为这是角度中的错误或代码中实现的一些奇怪的行为。我有同样的问题,并通过源代码调试只是为了找到这个:
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
还是blur
,都会在setValue上触发asyncValidator。
我没有选择,只能在每次setValue调用之前删除asyncValidator,然后再添加它。
尝试单独更新它们。
this.form.controls.name.setValue(data.name);
this.form.controls.comments.setValue(data.comments);
在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>
你为什么要做setValue
?
我建议你在得到回复时绑定值。如果响应为null或为空,则它将为空,否则将填充值。
码:
ngOnInit(){
this.http.get('/api')
.subscribe((data: any) => {
this.form = this.fb.group({
name: [data.name || '', [Validators.required], MyAsyncValidator],
comments: [data.comments || ''],
});
});
}