我正在使用 Angular 的反应形式。用例是使用来自 BE 的字段值和类型动态创建表单。此外,字段的验证器也来自 BE。 我可以动态创建表单,但动态添加验证器会给我带来错误。
control.addValidators(Validators[validator]()
其中验证器是一个动态字符串,可以是“pattern”、“required”、“minLength”等。
我遇到的错误是
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Validators'.
No index signature with a parameter of type 'string' was found on type 'typeof Validators'.
您可以尝试使用
keyof Validators
这解决了问题!
const test = 'required';
control.addValidators(Validators[<keyof Validators>test]);