Search code examples
angulartypescriptangular-forms

Dynamically add control to form in angular


I've created this form here: https://stackblitz.com/edit/angular-ay58g9

I'm getting an error when selecting the option from select menu that I'm not able to solve.

Also, I want the output like this:

When 'form data' selected in dropdown:
[
  data_type: 'form_data',
  form_data: {
    firstname: "saurabh",
    lastname: "Sharma"
  }
]

When 'form data' selected in dropdown:
[
  data_type: 'raw_data',
  raw_data: {
    email: "saurabh@gmail.com",
    contactno: "9999999999"
  }
]

COuld you please look into it and tell me what I'm doing wrong?


Solution

  • I adjusted your example a bit: https://stackblitz.com/edit/angular-avcytw

    Your dynamically added formControls are within formGroups. Therefore the most important thing is to add formGroupName to the inputs parent elements.

    <div *ngIf="this.form.get('form_data')" formGroupName="form_data">
            <input type="text" formControlName="firstname" placeholder="firstname">
            <input type="text" formControlName="lastname"  placeholder="lastname">
        </div>
    

    Also the initial form needed to be adjusted:

        this.form = this.formBuilder.group({
          data_type: ["", Validators.required],
          // form_data: new FormControl(),
          // raw_data: new FormControl()   
        }); 
    

    form_data: new FormControl() and raw_data: new FormControl() caused the ngIfs to render before you add the corresponding form controls dynamically. Thats why there were errors indicating the formControls can not be found.