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?
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);
}
Wouldn't something like this work:
formArray = new FormArray([formArray.at(index)]);
Edit:
No, it would not work well because the FormArray will lose connection to parent control as @yurzui said. So @nash11 's answer is the correct one.
As an addition to the accepted answer I would like to point out that in the occasion where someone has subscribed to changes of any deleted member the subscription would still be alive resulting in a memory leak.
Example of the above situation.
There is no built-in method in Angular to achieve this.
One possibility would be to keep only one array item at itemIndex
with slice()
and set the FormArray
value with the new array after clearing it with the clear()
method (available in Angular 8+):
const arrayValue = this.form.get('myArray').value;
this.form.get('myArray').clear();
this.form.get('myArray').push(this.fb.control(arrayValue.slice(itemIndex, itemIndex + 1)[0]));