【发布时间】:2019-02-04 12:08:27
【问题描述】:
我有一个 Angular(v7) 响应式表单(可能与纯模板表单相同)。
带有type="number" 的<input> 将重新渲染并运行模糊验证。
在<input> 旁边的错误反馈<div> 中有一个值建议按钮,单击该按钮将使用建议值(由异步验证器提供)填充输入。
但是,如果您第一次单击该按钮,<input> 的模糊会触发整个元素的重新渲染,因此对输入没有影响。您必须再次单击该按钮才能使其工作。
我没有找到任何禁用此重新渲染行为的选项。
.ts 文件:
ngOnInit(): void {
this.newPlanForm = this.formBuilder.group({
plan_id: [
{
value: this.plan.plan_id,
disabled: !this.plan.insurer_id,
}, {
validators: [Validators.required, this.planIdSyntaxValidator.bind(this)],
asyncValidators: this.planIdDuplicationValidator.bind(this),
// updateOn: 'blur' // this is my hacky solution. The original problem occours without it
}
],
...
});
}
planIdDuplicationValidator(control: AbstractControl): Observable<ValidationErrors | null> {
// duplication check
...
}
fillInSuggestedPlanId(): void {
this.form.plan_id.setValue(this.form.plan_id.errors.duplicatePlanId);
}
// convenience getter for easy access to form fields
get form() {
return this.newPlanForm.controls;
}
HTML:
<form [formGroup]="newPlanForm">
...
<label for="plan_id">Plan ID<sup>*</sup></label>
<input type="number" class="form-control" id="plan_id" name="plan_id"
[ngClass]="{ 'is-invalid': form.plan_id.errors }"
formControlName="plan_id"/>
<div class="invalid-feedback" *ngIf="form.plan_id.dirty && form.plan_id.errors">
<p *ngIf="form.plan_id.errors.duplicatePlanId">
This plan ID is already taken. Next available is
<a (click)="fillInSuggestedPlanId()" class="btn-link">
{{suggestedPlanID}}
</a>
</p>
</div>
...
</form>
【问题讨论】:
-
尝试从验证器数组中删除 updateOn:'blur' 属性
-
@Chellappan 抱歉,这是我的 hacky 解决方案,实际上没有它就会出现问题。 (顺便说一句,它是控件本身的配置属性,而不是验证器级别。)请参阅我的编辑。
-
请创建一个演示来显示这个问题:)
-
@AJT_82 添加了演示。请输入除“12345”以外的任何内容,然后单击下面的链接按钮,您将看到有问题的行为。
-
@MylesFong 我一定会看看的。刚开始工作,所以我想我需要工作 :D 希望你能等一下,稍后我会尽力帮助你:)
标签: angular angular-reactive-forms