Search code examples
angulartypescriptangular8angular-reactive-forms

Remove value from FormControl based on value


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

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

Solution

  • 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