Home > Software engineering >  Get error: Cannot find control with path: 'excludedPeriods -> 0 -> dateTo'
Get error: Cannot find control with path: 'excludedPeriods -> 0 -> dateTo'

Time:09-26

I am trying to use a FormArray inside a FormGroup. My HTML looks like this:

<div nz-row nzGutter="10" formArrayName="excludedPeriods">
            <ng-container *ngFor="let period of excludedPeriodsList().controls; let i = index">

              <div [formGroupName]="i">
                <div nz-row nzGutter="10">
                  <div nz-col nzSpan>
                    <nz-form-item>
                      <nz-form-label nzSpan="24">Exclude From</nz-form-label>
                      <nz-form-control>
                        <nz-date-picker nzShowTime nzFormat="dd/MM/yyyy HH:mm" formControlName="dateFrom"
                          [style.width]="'100%'"></nz-date-picker>
                      </nz-form-control>
                    </nz-form-item>
                  </div>
                  <div nz-col nzSpan>
                    <nz-form-item>
                      <nz-form-label nzSpan="24">Exclude To</nz-form-label>
                      <nz-form-control>
                        <nz-date-picker nzShowTime nzFormat="dd/MM/yyyy HH:mm" formControlName="dateTo"
                          [style.width]="'100%'"></nz-date-picker>
                      </nz-form-control>
                    </nz-form-item>
                  </div>
                </div>
              </div>
            </ng-container>
          </div>

Inside the TypeScript:

To initialize the form, I was checking if the form already contains any value or not via service call and passing that value to the createForm function:

private _createForm(product?: IProduct): void {
    console.log('_createForm ~ product', product.excludedPeriods);
    this.segmentIds = product?.segmentIds ?? [];
    const excludedPeriods = product?.excludedPeriods ?? [];
    this.productForm = this.fb.group({
      activeFrom: [product?.activeFrom],
      activeTo: [product?.activeTo],
      excludedPeriods: this.fb.array(excludedPeriods),
    });
}

excludedPeriodsList(): FormArray {
    return this.productForm.get('excludedPeriods') as FormArray;
}

newExcludePeriod(): FormGroup {
    return this.fb.group({
      dateFrom: '',
      dateTo: ''
    });
}

addExcludedPeriod() {
    this.excludedPeriodsList().push(this.newExcludePeriod());
}

I could not figure out what have I done wrong here. Can someone please enlighten me and give me a solution?

CodePudding user response:

You have to provide the excludedPeriods value as FormGoup[] to the form array.

Solution 1: With .map()

this.productForm = this.fb.group({
  ...,
  excludedPeriods: this.fb.array(
    excludedPeriods.map(
      (x) =>
        this.fb.group({
          dateFrom: [x.dateFrom],
          dateTo: [x.dateTo],
        })
    )
  ),
});

Solution 2: With FormArray.push()

private _createForm(product?: IProduct): void {
  ...

  this.productForm = this.fb.group({
    ...,
    excludedPeriods: this.fb.array([]),
  });

  this.addFormGroupToExcludePeriodsList(excludedPeriods);
}

addFormGroupToExcludePeriodsList(
  excludedPeriods: { dateFrom: Date; dateTo: Date }[]
) {
  for (let excludePeriod of excludedPeriods) {
    this.excludedPeriodsList().push(
      this.fb.group({
        dateFrom: [excludePeriod.dateFrom],
        dateTo: [excludePeriod.dateTo],
      })
    );
  }
}

Demo Solution 1 & 2 @ StackBlitz

  • Related