ng-select在Angular 6中以编程方式删除元素

问题描述 投票:1回答:2

我正在尝试使用该程序从ng-select中删除所选元素。因为我们可以使用单击十字按钮删除它,但我们想在Angular 6中删除编程方式。请帮助我找到理想的解决方案。

enter image description here

angular typescript multi-select angular-ngselect
2个回答
0
投票

您的ng-selectselectedCityIds是2向绑定的,这就是[(ngModel)]表示法所做的。意思是,更改一个(GUI ng-select或class属性selectedCityIds)都会更改另一个。这是一个建议的解决方案:

我创建了一个文本输入,允许用户输入城市名称。

<label>Type name of city to delete</label>
<input type="text" [(ngModel)]="cityToDelete" style="margin-left: 10px" />

然后,您的deleteSingle方法是这样完成的:

// This is the property bound to the text input
cityToDelete: string = "";
deleteSingle () {
  // This will be the city to delete
  const city = this.cities2.find(c => c.name === this.cityToDelete);
  // If city with this name is found in list, then it's removed
  if(city != null) {
    console.log(city);
    this.selectedCityIds = this.selectedCityIds.filter(id => id !== city.id);
  }
}

Stackblitz here

尝试一下:

  1. 将“维尔纽斯”和“考纳斯”添加到ng-select
  2. 在文本输入中输入上述名称之一。
  3. 单击“按名称删除城市”

您将看到您键入的城市名称将从GUI中删除。该代码搜索了您的ng-select数据源,在您的示例中为cities2。如果在cities2中找不到用户输入名称的城市,则不采取任何措施。


0
投票

我已经添加了所有可用的方法。您可以在这里找到它们:https://stackblitz.com/edit/angular-yblxng

也可以在这里看看:https://github.com/ng-select/ng-select#change-detection

© www.soinside.com 2019 - 2024. All rights reserved.