javascript - 如何使用 FormBuilder 动态地将验证器添加到 Angular 2 - 4 中的表单中?

标签 javascript angular typescript

我正在使用 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/

相关文章:

javascript - 数据未在 React Native 中使用 Flatlist 渲染

javascript - 将包含单个整数的数组传递给 Uint8Array 会对传递给它的内容产生什么影响?

javascript - 如何使用 document.getElementById 和 getElementsByClassName 做 Jasmine 测试用例以显示无 css 属性

Angular 5 - 将服务限制为模块

Angular 6 : Can't bind to 'FormGroup' since it isn't a known property of 'form'

如果声明参数类型,TypeScript 函数实现会将参数类型降级为 `any`

javascript - 使用 jQuery 进行多复选框过滤

javascript - 如何在 Angular 中实现全局加载器

对象的 Angular 自然排序数组

javascript - 如何从 typescript 上的txt文件获取数据?