我创建了一个空数组,用于循环动态添加和删除表单上的文本框。
mobiles: Array<string> = [];
<ng-container *ngFor="let mobile of mobiles; index as i">
// Code
</ng-container>
在循环外,我有一个添加新文本框的按钮。
<button (click)="addElement()">
</button>
我在循环内有一个按钮,用于根据索引删除特定的文本框。
<button (click)="removeElement(i)">
</button>
addElement()
函数只是将一个空值压入数组的末尾。
this.mobiles.push('');
removeElement(index)
函数从数组中删除索引。
if (index in this.mobiles) {
this.mobiles.splice(index, 1);
}
此代码的问题在于,由于我的数组中的所有值都相同(空),splice()
不会删除指定索引处的元素,而是删除数组中的最后一个元素.因此,它还会删除最后一个文本框,而不是我单击的文本框。
我测试了在我的数组中推送非空值,但结果仍然相同。它只有在我推送不同的值时才能正常工作,例如:
this.mobiles.push(this.mobiles.length);
但是我不想使用这种方法,因为我打算用实际的电话号码填充这个数组。
还有其他选择吗?
我的 Angular 版本是 7.2.15。
谢谢!
最佳答案
该问题的一种解决方法是将每个值包装在一个对象中。 ngFor
循环中每个项目的值将成为对象的引用。由于这些引用都是不同的,因此将按预期删除目标项目。
使用这个界面:
interface Phone {
phoneNumber?: string;
}
您可以定义一个 Phone
对象数组:
mobiles: Array<Phone> = [];
addElement() {
this.mobiles.push({});
}
removeElement(index) {
this.mobiles.splice(index, 1);
}
get phoneNumbers() {
return this.mobiles.map(x => x.phoneNumber);
}
并编辑模板中的 phoneNumber
属性:
<button (click)="addElement()">Add phone</button>
<ng-container *ngFor="let mobile of mobiles; index as i;">
<div>
<input [(ngModel)]="mobile.phoneNumber" />
<button (click)="removeElement(i)">Remove element</button>
</div>
</ng-container>
参见 this stackblitz用于演示。
关于javascript - 所有数组值都相同时的拼接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58660809/