Prasenjit Saha
Prasenjit Saha

Reputation: 63

How to convert string to a object in typescript

I am making dynamic forms in Angular 6 . For that i am sending JSON from backend . PFB the json


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

I am making the forms in Typescript as follows. PFB the code

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

I am getting the problem in => data.syncValidators , as it is treated as a string . But it needs to be Validators.required .

How can i make the conversion so that 'data.syncValidators' will be taken as a method not as a string ?

Upvotes: 1

Views: 3064

Answers (2)

Harshit Tailor
Harshit Tailor

Reputation: 3281

You can use ternary

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

Upvotes: 0

SoroushNeshat
SoroushNeshat

Reputation: 674

create a factory to acheive that :

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

and use it like this :

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

Upvotes: 2

Related Questions