1

I'm tried to create dynamic reactive form using json file but didn't worked with me.

This the json file :

 "inputs":[
    {
      "formcontrol":"email",
      "validation":["required,email"]
    },
    {
      "formcontrol":"password",
      "validation":["required"]
    },
    {
      "formcontrol":"firstname",
      "validation":["required"]
    },
    {
      "formcontrol":"lastname",
      "validation":["required"]
    }
  ]

This what I tried :

for(let input of inputs ) // json data
{
   this.t.push(this.formBuilder.group({
      input.formcontrol: ['', input.validation],
   }));
}

I know what I did isn't correct but I have no clue how to solve this.

2 Answers 2

3

You need to add only formControl dynamically as per the formGroup like below -

inputs =[
    {
      "formcontrol":"email",
      "validation":["required,email"]
    },
    ....
  ];

  constructor(private fb: FormBuilder) { }

  ngOnInit(){
    this.SignupForm = this.fb.group({});
    let control = new FormControl('');

    for(let input of this.inputs) {
      this.SignupForm.addControl(input.formcontrol, control);
    } 

    console.log(this.SignupForm.value);
  }

Working Example Snippet

If needed you may refer official Documentation here

Sign up to request clarification or add additional context in comments.

1 Comment

Can you please answer this: stackoverflow.com/questions/74735567/…
0

Here's example of creating dynamic form controls

inputs: any = <json data>;
formGroup: FormGroup = new FormGroup({});

ngOnInit(): void {
    // process json data
    this.inputs.forEach(value => {
        this.formGroup.addControl(
            value.formcontrol, // control name
            new FormControl("", this.getValidators(value.validation))
        );
    });
}

// method that returns angular validators from strings
private getValidators(validatorsList: Array<string>): Array<ValidatorFn> {
    const validators: Array<ValidatorFn> = [];

    // map string validators to angular validators
    validatorsList.forEach((validator: string) => {
        switch (validator) {
           case "required":
               validators.push(Validators.required);
               break;
           case "email":
               validators.push(Validators.email);
               break;
           default:
           break;
        }
    });

    return validators;
}

I also created StackBlitz example, check console to see result.

2 Comments

Link only answers are never encouraged!
Sorry, fixed for now :)

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.