如何引发angular2表校验器 [英] How to trigger Form Validators in angular2
问题描述
在angular2我想,当一个又一个的控制改为触发校验器对于某些控件。是否有某种方式,我可以告诉的形式来重新验证?更妙的是,我可以要求具体领域的验证?
In angular2 I want to trigger Validators for some controls when a another control is changed. Is there some way that I can just tell the form to re-validate? Better still, can I request validation of specific fields?
例如:
鉴于复选框X和输入P.
输入P有有不同的特征X上的模型值的验证
当X被选中/取消我需要调用验证器上P的验证P上会看模型来确定X的状态,并相应确认P上。
Example: Given Checkbox X and input P. Input P has a validator that behaves differently based on the model value of X. When X is checked/unchecked I need to invoke the validator on P. The Validator on P will look at the model to determine the state of X and will validate P accordingly.
下面是一些code:
constructor(builder: FormBuilder) {
this.formData = { num: '', checkbox: false };
this.formGp = builder.group({
numberFld: [this.formData.num, myValidators.numericRange],
checkboxFld: [this.formData.checkbox],
});
}
this.formGp.controls['checkboxFld'].valueChanges.observer({
next: (value) => {
// I want to be able to do something like the following line:
this.formGp.controls['numberFld'].validator(this.formGp.controls['numberFld']);
}
});
任何人有一个解决方案?谢谢!
Anybody have a solution? Thanks!
推荐答案
我不知道如果你还在寻找一个答案,所以这里是我的建议:
I don't know if you are still looking for an answer, so here is my suggestions:
有一个看看这个:<一href=\"https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/model.ts#L116\"相对=nofollow>角2 - AbstractControl
我觉得你可以做的是以下内容:
I think what you could do is following:
this.formGp.controls['checkboxFld'].valueChanges.observer({
next: (value) => {
this.formGp.controls['numberFld'].updateValueAndValidity();
}
});
这会触发并运行验证。此外,状态得到更新。现在,你应该能够将您的验证逻辑进行磋商的复选框值。
This should trigger and run the validators. Furthermore the state gets updated as well. Now you should be able to consult the checkbox value within your validator logic.
希望这有助于!
编辑:更新的链接和榜样。而我在写我的回答code改变。
Updated link and example. Code changed while I was writing my answer.
EDIT_2:alpha.48改变EventEmitter.observer到EventEmitter.subscribe
EDIT_2: alpha.48 changes the EventEmitter.observer to EventEmitter.subscribe!
这篇关于如何引发angular2表校验器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!