简体   繁体   English

如何手动触发 Angular 2 输入验证?

[英]How to trigger Angular 2 input validation manually?

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 参考方法触发重新验证吗?

您可以更新 formControl 的有效性

form.controls['myControl'].updateValueAndValidity();

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();

我发现这要好得多

this.myForm.markAllAsTouched();

Angular 12 and the other answers didnt work for me..so i added a hidden button on the form Angular 12 其他答案对我不起作用..所以我在表单上添加了一个隐藏按钮

 <button type="submit" [style.visibility]="'hidden'" #submitBtn>Submit</button>

On the controller ViewChild this button. controller ViewChild这个按钮。

  @ViewChild('submitBtn') private buttonSubmit:ElementRef;

And force a click on the event i want.并强制单击我想要的事件。

  submitFormByKey(){
    this.buttonSubmit.nativeElement.click();
  }

This will trigger a submit and validate all.这将触发提交并验证所有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM