Unable to genrate dynamic form ionic

64 Views Asked by At

I want to generate dynamic form. Expected output:

 {"laboratories":[{"colArr":[{"col":"11"},{"col":"22"},{"col":"33"}]},{"colArr":[{"col":"5"},{"col":"423"}]}]}

laboratories is my main key, it count the number of rows. colArr is key of each row and inside colArr I have dynamic no of columns added with formcontrolname col

So as per above JSON: I have two rows (first row has 3 columns and second has two columns)

Code I have tried:

home.html

<form [formGroup]="laboratoryForm">
    <div formArrayName="laboratories">
      <ion-row *ngFor="let obj of laboratoryForm.controls.laboratories.controls; let i=index" style="background-color: red;">
        <div [formGroupName]="i">
          <div formArrayName="colArr">
            <ion-col *ngFor="let item of obj.controls.colArr.controls; let j=index" style="background-color: green;">
              <span [formGroupName]="j">
                <ion-input placeholder="Enter Input" formControlName="col"></ion-input>
              </span>
            </ion-col>
          </div>
        </div>
      </ion-row>
    </div>
  </form>

home.ts

public laboratoryForm: FormGroup;
  noOfRows = 0;
  constructor(public navCtrl: NavController, private _fb: FormBuilder) {
    this.laboratoryForm = this._fb.group({
      laboratories: this._fb.array([
        this._fb.group({
          colArr: this._fb.array([
            this._fb.group({
              col: ['']
            })
          ])
        })
      ]),
    });
    this.AddItemData();
  }

  AddItemData() {
    //Add new data to Form
    const control = <FormArray>this.laboratoryForm.controls['laboratories'];
    this.noOfRows++;
    control.push(this._fb.group({
      colArr: [this.addColData(3)]
    })
    );

  }

  addColData(noOfcolumns) {
    const docs = <FormArray>this.laboratoryForm.controls['laboratories'];
    for (let row = 0; row < this.noOfRows; row++) {
      var grp = <FormGroup>(docs.controls[row])
      const colArrReceived = <FormArray>grp.controls['colArr'];
      for (let indx = 0; indx < noOfcolumns; indx++) {
        var colGrp = <FormGroup>(colArrReceived.controls[indx]);
        colGrp.controls['col'].patchValue('');
      }
    }
  }

How can I find my mistake?

1

There are 1 best solutions below

0
chrismclarke On

You are iterating over controls that don't exist.

for (let indx = 0; indx < noOfcolumns; indx++) {
        var colGrp = <FormGroup>(colArrReceived.controls[indx]);
    }

The previous code only ever creates a single control, however your function takes any number to iterate over

          colArr: this._fb.array([
            this._fb.group({
              col: ['']
            })
          ])

Stackblitz at: https://ionic-blank-6yjgws.stackblitz.io/