2

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();
       }
      }
    }

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

We can run a loop of controls and check for value of each control. As it is a formarray, looping in this way over the controls works without any issue

1 Comment

Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?
0
deleteSVO(i: any) {
  const control = this.VOForm.get('VORows') as FormArray;
  control.removeAt(i);
  this.dataSource = new MatTableDataSource(control.controls)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.