问题描述
我正在尝试将验证器添加到 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
表单控件,我们必须在设置validators后调用this.formGroup.controls["firstName"].updateValueAndValidity();
动态.
this.formGroup.controls["firstName"].setValidators(Validators.required);this.formGroup.controls["firstName"].updateValueAndValidity();
DEMO 相同>
* 注意 *
updateValueAndValidity() 将触发 valueChanges 事件,即使该值并未真正改变(如果您从 valueChanges 订阅中调用它,则可能导致无限循环).您可以通过使用可选参数对象来防止这种情况:{ onlySelf: true, emitEvent: 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 添加验证器动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!