angularexceptremoveallformarray

How to remove all elements of a FormArray but one specific index?


Is there any built-in functionality in Angular, so that I can say:

remove all FormArray elements except at index 2

maybe something like 'RemoveRange" as known from other libs?


Solution

  • Angular does not have this functionality inbuilt. You can instead store the required value, clear the formArray and then push the stored value back into the now empty formArray

    keepOnly(index: number) {
      const valueToKeep = this.formArray.at(index);
      this.formArray.clear();
      this.formArray.push(valueToKeep);
    }