TypeScript. FormGroup FormArray - remove only one element object by value. Angular 2 4
Solution 1
FormArray
class has removeAt
which takes the index. If you do not know the index, you can do a workaround:
this.images.removeAt(this.images.value.findIndex(image => image.id === 502))
Solution 2
In Angular Reactive Forms, formArray
has a method called removeAt()
.
You can use it by passing an index that you want to delete:
delete(index){
this.array.removeAt(index)
}
``
Solution 3
if you want to remove a value for a particular Key from the FormGroup, You can use following code -
this.formGroupF.controls[value].patchValue(null)
user7337867
Updated on July 05, 2022Comments
-
user7337867 almost 2 years
this.formGroup = this.formBuilder.group({ images: this.fb.array([]) });
I add new element in this way:
this.images.push(new FormControl(new ImageCreateForm(this.imageResponse.id)));
get images(): FormArray { return <FormArray>this.formGroup.controls.images; }
My classes:
export class ImageCreateForm { id: number; constructor(id: number) { this.id = id; } } export class ImageResponse { id: number; url: string; }
When I added images, then my
{{ formGroup.value | json }}
is:"images": [ { "id": 501 }, { "id": 502 }, { "id": 503 } ]
I want to remove images (for example only image with
id=502
) fromformGroup
before when I send my form POST request. Is it possible? I tried usereset
method, but this remove all elements:this.images.reset({"id":image.id});
. Whereimage
it is aImageResponse
object.Result:
{"images": [ null, null, null ]}
, but I want:"images": [ { "id": 501 }, { "id": 503 } ]
-
Chris Halcrow over 5 yearsThis is the correct way to remove from a FormArray. Don't use formArray.controls[i].splice - that will remove the control from the array but the control values will remain on the
values
array of theFormArray
control. -
Julio Cesar Brito Gomes about 2 yearsThat way you are setting null for the value field of the form. But if you really want to remove an element completely, you can do it this way. this.form.removeControl('value'); I often use this for unit tests that have lines like these this.form.get('value')?.value