我创建了一个空数组,用于循环遍历以动态添加和删除表单上的文本框。
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>
有关演示,请参见此堆叠闪电战。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句