我正在Angular 6中制作动态表单。为此,我从后端发送JSON。 PFB的JSON



[
 {
  "controlType": "input",
  "label": "Test1",
  "key": "some1",
  "value": "This input is pre-populated",
  "syncValidators": "Validators.required"
 }
]




我在打字稿中制作表格如下。 PFB代码

this.dataList = JSON.parse(event.body); //Contains the JSON sent from backend
const formContent: any = {};

this.dataList.forEach(data => {
      formContent[data.key] = new FormControl(data.value ,data.syncValidators));
 });

this.exampleForm = new FormGroup(formContent);


我在=> data.syncValidators中遇到问题,因为它被视为字符串。但是它需要是Validators.required。

我如何进行转换,以便将'data.syncValidators'视为方法而不是字符串?

最佳答案

创建一个工厂来实现这一目标:

validatorFactory(validatorName:string){
     switch(validatorName){
          case "Validators.required" :
               return Validators.required;
          // add other validators like max , min , ....
          default : return null;
     }
}

并像这样使用它:
    this.dataList.forEach(data => {
      formContent[data.key] = new FormControl(data.value ,validatorFactory(data.syncValidators)));
    });

09-16 02:58