gpt4 book ai didi

javascript - Angular 7 - 从数组中拼接和删除(下拉值)

转载 作者:行者123 更新时间:2023-12-02 23:25:05 27 4
gpt4 key购买 nike

我有一个打开的下拉菜单,其中包含多个选项。我用两个创建了一个简单的pickList。我使用 splice 在单击按钮后从数组中删除选定的值,但当选择是多个时,splice 似乎会删除除所选值之外的所有值。

例如:在我的右侧列表中 - 如果我选择旧金山、迈阿密、波士顿和拉斯维加斯,然后将它们移至右侧选定的框。这很完美。

enter image description here

问题是选择波士顿和迈阿密,然后单击向左箭头进行删除,删除除所选之外的所有内容。我以前使用过 splice 但我不记得它忽略了数组中的项目。

我的代码组件如下所示:

<select [(ngModel)]="foundLocations" multiple="multiple">
<option *ngFor="let locOption of locations" [ngValue]="locOption" >
{{ locOption }}
</option>
</select>
<div class="selectButtons">
<button (click)="selectThese()">></button>
<br/>
<button (click)="removeThese()"><</button>
</div>
<select [(ngModel)]="selectedLocations" multiple="multiple">
<option *ngFor="let chosen of pickedLocationItems" [ngValue]="chosen" >
{{ chosen }}
</option>
</select>

在我的组件中看起来像:

  foundLocations: any;
selectedLocations: any = [];
pickedLocationItems: any = [];

locations: any = ["San Francisco", "Seattle", "Las Vegas", "Toronto", "Boston", "Miami", "Altantic City"];

selectThese() {
for (var i = 0; i < this.foundLocations.length; i++) {
this.checkSelLocation(this.foundLocations[i]);
}
}

checkSelLocation(x: any) {
console.log("Check sel locations");
console.log(x);
this.pickedLocationItems.push(x);
}

removeThese() {
for (var g = 0; g < this.selectedLocations.length; g++) {
this.pickedLocationItems.splice(g, 1);
}
}

我有一个 Stackblitz example here .

最佳答案

为了达到预期的结果,请更改您的removeThese方法,如下

  1. 您选择的拼接索引错误(因为g的索引是从0开始的,实际选择的位置可能不是从索引-0开始的)
  2. 首先通过indexOf查找索引
  3. 使用该索引进行拼接

removeThese() {
for (var g = 0; g < this.selectedLocations.length; g++) {
this.pickedLocationItems.splice(this.pickedLocationItems.indexOf(this.selectedLocations[g]), 1);
}
}

工作代码示例供引用-https://stackblitz.com/edit/angular-xwwevl?file=src/app/app.component.ts

关于javascript - Angular 7 - 从数组中拼接和删除(下拉值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56779606/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com