0

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: "[email protected]",
    contactno: "9999999999"
  }
]

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

2

2 Answers 2

0

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.

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

Comments

0

If you're using Reactive Forms with Angular, my suggestion is to look into using a FormArray.

profileForm = this.fb.group({
  firstName: ['', Validators.required],
  lastName: [''],
  formData: this.fb.array([
    this.fb.control('')
  ])
});

Angular Documentation: https://angular.io/guide/reactive-forms#dynamic-controls-using-form-arrays

Comments

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.