Angular 2 FormGroup添加验证器动态 [英] Angular 2 FormGroup Add Validators dynamic

查看:396
本文介绍了Angular 2 FormGroup添加验证器动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向FormContol动态添加验证器(不适用于初始化),并且不起作用....

代码:

 this.formGroup.controls["firstName"].validator = Validators.Required; 

有人做吗?

解决方案

尝试一下,它应该可以工作

this.formGroup.controls["firstName"].setValidators(Validators.required);

用于多个验证人

this.formGroup.controls["firstName"].setValidators([Validators.required, Validators.minLength(2)]);

但是这样做会覆盖初始化期间提供的所有验证器

编辑:

要立即用新添加的Validators反映表单控件,我们必须在动态设置验证器之后调用this.formGroup.controls["firstName"].updateValueAndValidity();.

this.formGroup.controls["firstName"].setValidators(Validators.required);
this.formGroup.controls["firstName"].updateValueAndValidity();

演示 >

*注意*

即使值没有真正改变,

updateValueAndValidity()也会触发一个valueChanges事件(如果从valueChanges订阅中调用它,则可能导致无限循环).您可以通过使用可选的参数对象来阻止这种情况:{onlySelf:true,酋长:false}

i'm tring to add validator to FormContol dynamic (not on initialization) and it's not work....

the code:

this.formGroup.controls["firstName"].validator = Validators.Required;

Did anyone do it?

解决方案

Try this, it should work

this.formGroup.controls["firstName"].setValidators(Validators.required);

For multiple validators

this.formGroup.controls["firstName"].setValidators([Validators.required, Validators.minLength(2)]);

But doing so will override any validators that are provided during initialization

EDIT :

To reflect the form controls with newly added Validators immediately, we have to call this.formGroup.controls["firstName"].updateValueAndValidity(); after setting validators dynamically.

this.formGroup.controls["firstName"].setValidators(Validators.required);
this.formGroup.controls["firstName"].updateValueAndValidity();

DEMO for the same

* NOTE *

updateValueAndValidity() will trigger a valueChanges event even if the value didn't really change (potentially resulting in an infinite loop, if you're calling it from within a valueChanges subscription). You can prevent that by using the optional parameter object: { onlySelf: true, emitEvent: false}

这篇关于Angular 2 FormGroup添加验证器动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆