例如,我有一个控件,它是一组单选按钮。
如果勾选了choice1或choice2,并且它与我在组件TS中的字段不兼容,那么自定义验证器应该拒绝用户操作并返回到以前的状态和值。
组件.ts
toFormGroup(properties: PropertyBase<string>[]): FormGroup {
const group: any = {};
properties.forEach(property => {
const validators = this.service.getValidatorsByProperty(property);
if (property.required) validators.push(Validators.required);
const formControl = group[property.key] = new FormControl(
{
property.value,
disabled: property.disabled || false
}
);
formControl
.valueChanges.pipe(takeUntil(/** comp destroyed */))
.subscribe(val => {
formControl.setValidators(validators);
// if validators fail then I reset formControl to its previous state and value
// else submit the changes
submit(val);
});
});
return new FormGroup(group);
}
验证器示例
export function myValidator(
theFieldINeedForMyCondition: any
): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
let forbidden = false;
if (theFieldINeedForMyCondition)
forbidden = true;
return forbidden ? { forbiddenValue: { value: control.value } } : null;
};
// Maybe reset state and value directly here ?
}
所以问题是:例如,如果我选中了选项2,我可以将选择设置为选项3吗?