打字稿。 FormGroup FormArray - 按值仅删除一个元素对象。 Angular 2 4

TypeScript. FormGroup FormArray - remove only one element object by value. Angular 2 4

this.formGroup = this.formBuilder.group({
    images: this.fb.array([])
});

我以这种方式添加新元素: this.images.push(new FormControl(new ImageCreateForm(this.imageResponse.id)));

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
   }
]

我想在发送表单 POST 请求之前从 formGroup 中删除图像(例如只有带有 id=502 的图像)。可能吗? 我尝试使用 reset 方法,但这会删除所有元素: this.images.reset({"id":image.id});。其中 image 它是一个 ImageResponse 对象。

结果:{"images": [ null, null, null ]},但我想要:

"images": [
   {
    "id": 501
   },
   {
    "id": 503
   }
]

FormArray class 具有采用索引的 removeAt。如果你不知道索引,你可以做一个解决方法:

this.images.removeAt(this.images.value.findIndex(image => image.id === 502))

在 Angular Reactive Forms 中,formArray 有一个名为 removeAt() 的方法。 您可以通过传递要删除的索引来使用它:

delete(index){
    this.array.removeAt(index)
}
``

如果您想从 FormGroup 中删除特定键的值,您可以使用以下代码 -

this.formGroupF.controls[value].patchValue(null)