Javascript 如何手动触发 Angular 2 输入验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44759005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to trigger Angular 2 input validation manually?
提问by Slimas Slimanauskas
I have two inputs: - First one on which I apply my custom validator - Second one which value I use in my custom validator (it is dynamic and editable)
我有两个输入: - 第一个我应用我的自定义验证器 - 第二个我在我的自定义验证器中使用的值(它是动态的和可编辑的)
If I apply my custom validator on the first input, then I focus the second one and change the value - I want to force first inputs re-validation...
如果我在第一个输入上应用我的自定义验证器,那么我关注第二个并更改值 - 我想强制第一个输入重新验证......
At the moment it only re-validates first input when I change the value... Any suggestions?
目前它只在我更改值时重新验证第一个输入......有什么建议吗?
At the moment when I focus the first input I can access it's reference:
在我关注第一个输入的那一刻,我可以访问它的参考:
<input
name="mEnd"
class="form-control"
[(ngModel)]="endDate"
...
#endDateInput="ngModel"
(focus)="clog(endDateInput)"
>
I wonder can I trigger re-validation using the input formControl reference methods?
我想知道我可以使用输入 formControl 引用方法触发重新验证吗?
回答by Robin Dijkhof
You can update the validity of a formControl
您可以更新 formControl 的有效性
form.controls['myControl'].updateValueAndValidity();
form.controls['myControl'].updateValueAndValidity();
回答by Mariia Bilyk
If you have template-driven form you can access form throw ViewChild decorator:
如果您有模板驱动的表单,您可以访问表单 throw ViewChild 装饰器:
@ViewChild('myForm') public form: NgForm;
then, validate one field or the whole form group using method mentioned above:
然后,使用上述方法验证一个字段或整个表单组:
this.form.controls.myControl.updateValueAndValidity();
回答by C.Ikongo
I found this to be much better
我发现这要好得多
this.myForm.markAllAsTouched();

