我正在使用 FormBuilder 构建表单:
this.myForm = this.fb.group({
'name': new FormControl(null, Validators.min(5)),
'description': new FormControl(null, Validators.min(60))
});
问题是我还应该验证是否需要它,并且我通过这样构建的 map 从配置中获取它:
map = new Map<string, boolean>();
map.set('name', true);
map.set('description', false);
问题可以通过以下方式解决:
this.myForm = this.fb.group({
'name': this.map.get('name') ? new FormControl(null, Validators.compose([Validators.required, Validators.min(5)])) : new FormControl(null, Validators.min(5)),
'description': this.map.get('description') ? new FormControl(null, Validators.compose([Validators.required, Validators.min(60)])) : new FormControl(null, Validators.min(60))
});
这是可行的,但想象一下在一个包含多个表单和很多字段的大型应用程序中,这种方式确实很不舒服。理想情况下它看起来像这样:
Object.keys(this.myForm.controls).forEach(key => {
if (map.get(key)) {
this.myForm.get(key).setValidators(this.myForm.get(key).getValidators().push(Validators.required))
}
});
当然这样不行。因此,如果有人已经解决了这个问题,或者有一个好的方法来做上述事情,我将非常感谢你。提前致谢!!!
更新:问题可以简化为“如何获取与 FormControl 关联的所有验证器”。我认为这个问题没有明确的解决方案 --> https://github.com/angular/angular/issues/13461
最佳答案
这是一个简单的解决方案,我在评论中解释了它:
Object.keys(this.myForm.controls).forEach(key => {
// if it needs to be required
if (map.get(key)) {
// you have first to check if it already contains validator.required.
let validators = this.myForm.controls[key].validator(this.myForm.controls[key]);
// if it contains it -> {required: true};
// if it doesn't contains it you can now add the required validator
if(validators && !validators.required){
let exisitingValidators = this.myForm.controls[key].validators;
this.myForm.controls[key].setValidators(Validators.compose([...existingValidators ,Validators.required]));
// call updateValueAndValidity to apply the new validators on the control
this.myForm.controls[key].updateValueAndValidity();
}
});
希望有帮助:)
关于javascript - 如何使用 FormBuilder 动态地将验证器添加到 Angular 2 - 4 中的表单中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46852063/