首页 > 解决方案 > 检查来自组件的自定义反应中的当前验证器

问题描述

在我的一个表单组件中,比如说MyParentFormComponent,我需要知道其父组件使用了哪些验证器 例如

const fc = new FormControl('', [Validators.email, Validators.required]);

因此,在我的表单控件组件中,我想知道这两个验证器是否存在。原因是这个来自组件的自定义是其他表单组件的包装器,所以我想将这些验证器传递给它的子组件。

所以,我试过:

export MyParentFormComponent implements OnInit, ControlValueAccessor {
    @Input() formControlName: string;

    constructor(@Optional() private controlContainer: ControlContainer) {}

    ngOnInit(): void {
        const control = this.controlContainer.control.get(formFieldName);
        const validators = control.validator(''); // problems!!!
    }
}

演示

首先,该control.validator函数不需要字符串,在我的 IDE 中,我收到以下消息:

在此处输入图像描述

显然它想要一个 AbstractControl。但是当我按如下方式修复此错误时

control.validator('' as any);

它返回

{ required: true }

它只包含Validators.required. 其他人都不在里面。

所以我觉得这可能不是获取验证者信息的正确途径。有什么建议我可以得到这个列表吗?

更新:control.validator不是属性而是函数

在此处输入图像描述

标签: angularangular-reactive-forms

解决方案


推荐阅读