如何将动态验证器添加到角度反应表单控件

问题描述 投票:0回答:1

我正在使用 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'.
javascript angular typescript angular-reactive-forms
1个回答
0
投票

您可以尝试使用

keyof Validators
这解决了问题!

const test = 'required';
control.addValidators(Validators[<keyof Validators>test]);

stackblitz 没有给出此代码的错误

© www.soinside.com 2019 - 2024. All rights reserved.