我希望能够暂时禁用整个表单的验证。注意:我不想禁用实际的表单...
我能找到的最接近的是手动 remove and add them as described here ,但这对于复杂的表单来说相当尴尬。
this.form = this.formBuilder.group({
email: ['', Validators.compose([Validators.required, Validators.email])],
password: ['', Validators.compose([Validators.required, Validators.minLength(8)
])]
});
有类似的吗?
this.form.disableValidators() // ???
最佳答案
您可以在组件中使用 bool 属性。
validationEnabled = true;
然后,当您定义控件时,
emailValidators = Validators.compose([Validators.required, Validators.email]);
passwordValidators = Validators.compose([Validators.required, Validators.minLength(8);
this.form = this.formBuilder.group({
email: ['', this.validationEnabled ? emailValidators : null],
password: ['', this.validationEnabled ? passwordValidators : null]
});
并根据需要设置属性。
这种方法的一个缺点是,当您想要切换时,您需要重建表单。
如果您想在创建表单后执行此操作,则需要使用上面链接的 API 中的方法 https://angular.io/api/forms/AbstractControl#setValidators 。
关于javascript - Toggle Angular 4/5 中的表单验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48445555/