TypeScript。 FormGroup FormArray - 按值删除一个元素对象。角2 4
问题描述:
this.formGroup = this.formBuilder.group({
images: this.fb.array([])
});
我以这种方式添加新的元素: this.images.push(new FormControl(new ImageCreateForm(this.imageResponse.id)));
TypeScript。 FormGroup FormArray - 按值删除一个元素对象。角2 4
get images(): FormArray {
return <FormArray>this.formGroup.controls.images;
}
我的课:
export class ImageCreateForm {
id: number;
constructor(id: number) {
this.id = id;
}
}
export class ImageResponse {
id: number;
url: string;
}
当我添加的图像,然后我{{ formGroup.value | json }}
是:
"images": [
{
"id": 501
},
{
"id": 502
},
{
"id": 503
}
]
我想删除图片(例如只有图像id=502
)从formGroup
之前,当我发送我的表单POST请求。可能吗? 我试过用reset
的方法,但是这个删除了所有元素: this.images.reset({"id":image.id});
。其中image
它是一个ImageResponse
对象。
结果:{"images": [ null, null, null ]}
,但我想:
"images": [
{
"id": 501
},
{
"id": 503
}
]
答
FormArray
类有removeAt
这需要索引。如果您不知道索引,则可以采取以下解决方法:
this.images.removeAt(this.images.value.findIndex(image => image.id === 502))