如何在打字稿中将字符串转换为对象

时间:2018-09-05 05:22:23

标签: javascript angular typescript angular6

我正在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中遇到问题,因为它被视为string。但这需要是Validators.required。

我如何进行转换,以便将“ data.syncValidators”作为一种方法而不是字符串?

2 个答案:

答案 0 :(得分:2)

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

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)));
    });

答案 1 :(得分:0)

您可以使用三元

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