简体   繁体   English

将字符串转换为Angular2 Form Validator类型

[英]Casting a string to an Angular2 Form Validator type

I'm using Angular 7 with Dynamic Forms 我正在将Angular 7与动态表单一起使用

I store some form configs such as input: "text" etc to construct my forms. 我存储一些表单配置,例如输入:“ text”等,以构造表单。 These are stored on a database. 这些存储在数据库中。 I store the validation as validator: "Validators.required". 我将验证存储为验证器:“ Validators.required”。 Now when I want to construct my dynamic forms and assign the validation to a form control using: 现在,当我要构造动态表单并将验证分配给表单控件时,可以使用:

validations.forEach(valid => {
   validList.push(valid.validator);
});
return Validators.compose(validList);

I get the following error: Screenshot 我收到以下错误: 屏幕截图

Now I'm assuming this is because I have Validators.required stored as a string which causes it to fail since it is not actually of type Validator which I've imported from angular/forms. 现在,我假设这是因为我将Validators.required存储为字符串,这导致它失败,因为它实际上不是我从angular / forms导入的Validator类型。

To my question: How can I convert the stored string to the Validators type. 我的问题是:如何将存储的字符串转换为Validators类型。 I've tried using castValidator = (valid.validator as Validators); 我试过使用castValidator = (valid.validator as Validators); which gave me the same error. 这给了我同样的错误。

I've thought about just doing a switch statement which checks the string then pushes the relevant Validators into the array, but that seems like a poor solution. 我考虑过只做一个switch语句,先检查字符串,然后将相关的Validators推入数组,但这似乎是一个糟糕的解决方案。 I would have to account for every Validator type, not even thinking about custom validation. 我将不得不考虑每种Validator类型,甚至不必考虑自定义验证。

If data is saved in the form of string and data is in the form of key value pair. 如果数据以字符串形式保存并且数据以键值对形式保存。 Then you will have to parse what you get from the database using JSON.parse(). 然后,您将不得不使用JSON.parse()解析从数据库中获得的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM