javascript - 所有数组值都相同时的拼接问题

标签 javascript arrays angular typescript

我创建了一个空数组,用于循环动态添加和删除表单上的文本框。

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。

谢谢!

演示:https://stackblitz.com/edit/angular-phgo61

最佳答案

该问题的一种解决方法是将每个值包装在一个对象中。 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/

相关文章:

javascript - crossfilter.js 和 dc.js 更新回调组更改图表

javascript - node-webkit 加载模块失败

javascript - 使用本地存储的多个 key

javascript - 包装 float 元素后最小化行,同时最小化宽度

javascript - 带有对象的嵌套数组,lodashmeanBy

javascript - 对于 JavaScript 多维数组的深拷贝,深入一层似乎就足够了。这是真的吗?

angular - 如何计算重试运算符是否执行了次数,是否发生错误异常

javascript - OWL Carousel afterMove 获取 img alt

java - 在 Java 二维数组中查找最小值和最大值

angular - 如何使特定单元格在 primeNG 的内联可编辑行中不可编辑