Home > Software engineering >  Remove value from FormControl based on a Key in Angular 8
Remove value from FormControl based on a Key in Angular 8

Time:09-17

console log of Product Form

    let desc = "Ticket stock"
// let index = this.productForm.controls.findIndex((control) => control.pristine);
const index = (this.productForm as FormArray).controls.findIndex(
  (control) => control.invalid
);
console.log(index);
this.productForm.removeAt(index);

I need to remove the element from productForm based on Key "Ticket stock", but I'm able to remove items only based on invalid,pristine,dirty etc.

CodePudding user response:

You are close to the answer.

  1. Specify the control as FormGroup type.
  2. Access the productDesc control from FormGroup and get its value to compare.
removeProduct() {
  let desc = 'Ticket stock';

  const index = (this.productForm as FormArray).controls.findIndex(
    (control: FormGroup) => control.controls.productDesc.value == desc
    // Or
    // (control: FormGroup) => control.controls['productDesc'].value == desc
  );
  console.log(index);

  if (index > -1)
    this.productForm.removeAt(index);
}

Demo @ StackBlitz

  • Related