【发布时间】:2021-07-14 11:48:03
【问题描述】:
我有以下表格。 arr 是 FormBuilder 的列表。
get arr() {
return this.form.get('arr') as FormArray;
}
this.form = this.fb.group({
id: this.fb.control(''),
name: this.fb.control('', Validators.required),
arr: this.fb.array([], Validators.minLength(1)),
});
public removeArr(idx: number) {
this.arr.removeAt(0);
}
如您所见this.arr.removeAt(0),我试图从列表中删除第一个arr,但它总是删除最后一个元素。甚至我将其更改为其他内容,例如 this.arr.removeAt(2),而不是删除第三个元素,而是删除最后一个元素。
如何删除idx 给出的任何元素,而不是总是删除最后一个元素。
注意:
看起来问题与 trackby 功能有关。
<form *ngIf="form" [formGroup]="form">
<mat-form-field appearance="outline">
<mat-label>Name</mat-label>
<input type="text" matInput formControlName="name" required />
</mat-form-field>
<div
class="arr-row"
*ngFor="let control of arrControls; let i = index; trackBy: trackByIndex"
[formGroupName]="i"
>
<mat-form-field appearance="outline">
<mat-label>Name</mat-label>
<input type="text" matInput formControlName="name" required />
</mat-form-field>
<button mat-icon-button type="button" (click)="removeArr(i)">
<mat-icon>delete</mat-icon>
</button>
</div>
</form>
trackByIndex: TrackByFunction<FormControl> = (index, _) => index;
如果我将 trackby 函数更改为
trackByIndex: TrackByFunction<FormControl> = (index, v) => v.value.id;
然后它可以工作但并非所有元素都有id,所以我不能在这里使用id。
【问题讨论】:
-
能否请您为此创建一个演示,我不明白为什么这段代码不起作用...
-
请查看备注。
-
请在stackbliz中模拟这个问题,方便调试。
标签: angular angular-reactive-forms formarray