Home > Mobile >  remove formarray element reactive forms angular
remove formarray element reactive forms angular

Time:12-16

I am trying to remove an array element from an formArray in angular reactive form as i dont want to display empty array element. I need to remove the element whose all controls contain null value or false. I dont want to remove the element even if any of its control contains a value other that the once specified.

this.accounts is formArray. I am trying to use the object.keys but not able to retrieve the element that does not contain values

I have tried something below. Could you

  if(this.readonly) {
      for (const control of this.accounts.controls) {
       const result  =  Object.keys(control).find((key) => (control[key] != null || true));
       if(!result) {
       // this.accounts.controls.splice();
       }
      }
    }

CodePudding user response:

Since you already have the control. You can just access the value on that control.

if(this.readonly) {
   for (const control of this.accounts.controls) {
     const result  =  control.value != null;
     if(!result) {
       // this.accounts.controls.splice();
     }
   }
}

Also instead of splice(). I would suggest using removeAt() on the the formArray it self. https://angular.io/api/forms/FormArray#removeat

Because after splice you would also have to call updateValueAndValidity for the change detection to run.

CodePudding user response:

(<FormArray>this.accounts).controls.forEach((el, i) => {
    if(el.value === null || el.value === false) {
(<FormArray>this.accounts.controls).removeAt(i);
 }
})
  • Related