如何在 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.
这是一些代码:
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:
看看这个:Angular2 - 抽象控件
我认为您可以执行以下操作:
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.
希望这有帮助!