在 Angular 中动态使用 setValidators 后如何不丢失初始化的验证器?
How to not lose the initialized Validators after using setValidators Dynamically in Angular?
我有一个父组件,我在其中创建了一个 FormControl 数组并使用 Validations.required Validator 对其进行了初始化。
在子组件中,我根据父组件 (true/false) 的输入添加动态验证器,但添加该验证器将从控件中删除 'required'。
如何在表单控件中保留初始化和后来添加的验证器?
根据官方文档
Sets the synchronous validators that are active on this control. Calling this overwrites any existing sync validators.
因此请务必记住,通过使用此方法,您将覆盖现有的验证器,因此您将需要包括所有 need/want 用于要重置的控件的验证器。
官方文档:https://angular.io/api/forms/AbstractControl#setValidators
SetValidators 将用您设置的任何内容覆盖验证器。您需要做的是附加额外的验证器来保持当前验证器的完整性。请参阅下面的代码来执行此操作。
this.<<formControl>>.setValidators([
this.newValidator(),
this.<<formControl>>.validator
]);
我有一个父组件,我在其中创建了一个 FormControl 数组并使用 Validations.required Validator 对其进行了初始化。
在子组件中,我根据父组件 (true/false) 的输入添加动态验证器,但添加该验证器将从控件中删除 'required'。
如何在表单控件中保留初始化和后来添加的验证器?
根据官方文档
Sets the synchronous validators that are active on this control. Calling this overwrites any existing sync validators.
因此请务必记住,通过使用此方法,您将覆盖现有的验证器,因此您将需要包括所有 need/want 用于要重置的控件的验证器。
官方文档:https://angular.io/api/forms/AbstractControl#setValidators
SetValidators 将用您设置的任何内容覆盖验证器。您需要做的是附加额外的验证器来保持当前验证器的完整性。请参阅下面的代码来执行此操作。
this.<<formControl>>.setValidators([
this.newValidator(),
this.<<formControl>>.validator
]);