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
) from formGroup
before when I send my form POST request. Is it possible?
I tried use reset
method, but this remove all elements:
this.images.reset({"id":image.id});
. Where image
it is a ImageResponse
object.
Result: {"images": [ null, null, null ]}
, but I want:
"images": [
{
"id": 501
},
{
"id": 503
}
]
答案 0 :(得分:65)
FormArray
类有removeAt
,它取索引。如果您不知道索引,可以执行解决方法:
this.images.removeAt(this.images.value.findIndex(image => image.id === 502))
答案 1 :(得分:4)
在Angular反应形式中,formArray
有一个称为removeAt()
的方法。
您可以通过传递要删除的索引来使用它:
delete(index){
this.array.removeAt(index)
}
``
答案 2 :(得分:0)
如果要从 FormGroup 中删除特定键的值,可以使用以下代码 -
this.formGroupF.controls[value].patchValue(null)