1

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 ?

2 Answers 2

2

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)));
    });
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thats for the reply @Harshit . But there can be array of validator like , new FormControl(data.value ,Validators.required , Validators.email ) ;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.