我如何 add/remove 验证器有条件地以反应形式出现?
How can i add/remove validators conditionally in reactive forms?
我有这样的反应形式
this.form = this.formBuilder.group({
...
email: [],
receiveNewsletter: [],
...
})
我希望所有字段都是可选的,除非用户选中 receiveNewsletter
,电子邮件字段应该是必需的。我该怎么做?
您必须观察复选框的值,并根据 receiveNewsletter
的值添加或删除所需的验证器
this.form.controls.receiveNewsletter.valueChanges.subscribe(value => {
if(value){
this.form.controls.email.addValidators(Validator.required);
} else {
this.form.controls.email.removeValidators(Validator.required);
}
this.form.controls.email.updateValueAndValidity(); //remember to add this to update the form control state
})
我有这样的反应形式
this.form = this.formBuilder.group({
...
email: [],
receiveNewsletter: [],
...
})
我希望所有字段都是可选的,除非用户选中 receiveNewsletter
,电子邮件字段应该是必需的。我该怎么做?
您必须观察复选框的值,并根据 receiveNewsletter
this.form.controls.receiveNewsletter.valueChanges.subscribe(value => {
if(value){
this.form.controls.email.addValidators(Validator.required);
} else {
this.form.controls.email.removeValidators(Validator.required);
}
this.form.controls.email.updateValueAndValidity(); //remember to add this to update the form control state
})