Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access formArray of FormGroup in *ngFor in angular?

I am using nested FormControl using FormArray. My Form is like this :

let form = new FormGroup({
   name: new FormControl(),
   email: new FormControl(),
   Addresses : new FormArray([
      new FormGroup({
         building: new FormControl(),
         society : new FormControl(),
      }),
      new FormGroup({
         building: new FormControl(),
         society : new FormControl(),
      })
      new FormGroup({
         building: new FormControl(),
         society : new FormControl(),
      })
   ])
})



addNewAddress() {
   let newAddress = new FormGroup({
      building: new FormControl(),
      society : new FormControl(),
   });
   this.form.get("addresses").push(newAddress)
}

And In HTML Template

<div *ngFor="let controlGroup of form.get('addresses').controls; let i=index">
   <ng-container [formGroup]="controlGroup">
     <input type="text" formControlName="building" />
     <input type="text" formControlName="society" />
   </ng-container>
</div>

**But Above Code returns Build Error like controls does not exist on abstractControl. **

So I convert form.get('addresses') into FormControl using this getter Melthod.

get addressArray() : FormArray {
    return form.get('addresses') as FormArray
}
//And use it in HTML like this

<div *ngFor="let controlGroup of addressArray.controls; let i=index">
   <ng-container [formGroup]="controlGroup">                             <== now here is build error
     <input type="text" formControlName="building" />
     <input type="text" formControlName="society" />
   </ng-container>
</div>

After that Conversion. New Build Error raised that controlGroup does not contain this methods : addControl, removeCotnrol and ...

Because addressArray.**controls** returns array of abstractControl instead of FormControl and [formGroup] directive needs FormControl.

How can I define Type in *ngFor like this :

let (controlGroup: FormControl) of addressArray.controls; let i=index

Is that Possible or not ?

Please Help me.

like image 401
Mayur Kukadiya Avatar asked Sep 05 '25 16:09

Mayur Kukadiya


1 Answers

You can Use that with Type in the same way you used like addressArray.controls

Here is the Full Code :

let form = new FormGroup({
   name: new FormControl(),
   email: new FormControl(),
   Addresses : new FormArray([
      new FormGroup({
         building: new FormControl(),
         society : new FormControl(),
      }),
      new FormGroup({
         building: new FormControl(),
         society : new FormControl(),
      })
      new FormGroup({
         building: new FormControl(),
         society : new FormControl(),
      })
   ])
})



addNewAddress() {
   let newAddress = new FormGroup({
      building: new FormControl(),
      society : new FormControl(),
   });
   this.form.get("addresses").push(newAddress)
}

get addressArray() : FormArray {
    return form.get('addresses') as FormArray
}

get addressControlsArray() : FormGroup[] {
    return this.addressArray.controls as FormGroup[]
}

In HTML

<div *ngFor="let controlGroup of addressControlsArray; let i=index">
   <ng-container [formGroup]="controlGroup">
     <input type="text" [formControlName]="building" />
     <input type="text" [formControlName]="society" />
   </ng-container>
</div>

And You can iterate through all formField to clear all it's validator like this :

nestedFormFieldIterator(formGroup: FormGroup | FormArray, action: "ClearValidation" | "MarkAsDirty"): void {
    Object.keys(formGroup.controls).forEach(key => {
      const control = formGroup.controls[key] as FormControl | FormGroup | FormArray;
      if (control instanceof FormControl) {
        // console.log(`Clearing Validators of ${key}`);
        if (action == "ClearValidation") {
          control.clearValidators();
        }
        if (action == "MarkAsDirty") {
          control.markAsDirty();
        }
        control.updateValueAndValidity();
      } else if (control instanceof FormGroup || control instanceof FormArray) {
        // console.log(`control '${key}' is nested group or array. calling clearValidators recursively`);
        this.nestedFormFieldIterator(control, action);
      }
    });
  }
like image 148
Mayur Kukadiya Avatar answered Sep 07 '25 18:09

Mayur Kukadiya