0

TYPESCRIPT

createFormGroup() {
    this.itemsForm = [this.itemsFormGroup];

    return this.fb.group({
      items: this.fb.array([this.itemsFormGroup])
    });
  }
          get itemsFormGroup() {
            return this.fb.group({
              width: [null, Validators.compose([Validators.required, Validators.pattern(/^\d*(\.\d{0,2})?$/)])],
              no_of_items: [null, Validators.required],
              height: [{ value: null, disabled: this.isDisabled }, (!this.isDisabled ?
                Validators.compose([Validators.required, Validators.pattern(/^\d*(\.\d{0,2})?$/)]) : null)]
            });
          }
        
      addToList(ctrl: any) {
        ctrl.push(this.itemsFormGroup);
      }

  resetForm() {
    const frmArray = this.formGroup.get('items') as FormArray;
    frmArray.clear();
}

HTML

<button nz-button type="button" nzType="link" class="btn btn-secondary mr-2 reset" (click)="resetForm();">

<i nz-icon nzType="plus" nzTheme="outline" (click)="addToList(formGroup.get('items'))"></i>

How to reset the formarray in angular? What I'm trying to do is when I try to click the reset it should display one item. for example I try to append 3 item then try to reset it should reset to one item instead or removing all. How do I fix it?

I'm not sure if this correct:

const frmArray = this.formGroup.get('items') as FormArray;
frmArray.clear();
frmArray.push(this.itemsFormGroup);

What I did is to get the formArray then I clear on it then push the new itemsFormGroup

  • Does `frmArray.clear()` working for you? the approach you are using is fine clear the array and push a new array. – Kamran Khatti Aug 04 '21 at 08:38
  • yes. but is there another way? instead of clearing the array then pushing a new array. –  Aug 04 '21 at 08:49

0 Answers0