【问题标题】:Remove unselected value from dropdown array - ngx-select-dropdown从下拉数组中删除未选择的值 - ngx-select-dropdown
【发布时间】:2021-06-06 13:21:26
【问题描述】:

context:使用 ngx-select-dropdown 的 Angular 应用程序。用户可以选择多个值,这些值被分类到“桶”中并发送到 api。

问题:我无法从结束数组中删除选定的项目 - this.filterState。我添加了一项检查以确保一个项目不能被多次添加 - 单击以选择该项目并单击以取消选择该项目。我认为这是删除带有splice 的项目的好时机,因为如果它已经存在于数组中,用户会单击以取消选择 - 但是,下拉列表不会传递它只是删除的取消选择对象的值它来自下拉列表的值数组。

  const index = this.filterState[convertedParam].indexOf(value);

  if (index === -1) {
    this.filterState[convertedParam].push(value);
  }

建议的解决方案:我认为它需要在事件更改时与下拉值对象和先前发送到 api 的数组进行某种比较。

最终目标:能够在排序后的数组中添加和删除对象

Here is a stackblitz that I put together...

app.component.ts

  handleFilterChange(prop: string, value: any): void {

// I think the comparison with "value" and whats already in "this.filterState" will need to be done here?

    let field = this.fields.find(f => f.name === prop);

    if (field.params) {
      value.forEach(v => this.setFilterState(v.type, v, field));
    } else {
      this.setFilterState(prop, value, field);
    }
    console.log("SUBMITTED SORTED VALUES", this.filterState);
  }

  setFilterState(prop: string, value: any, field: Field): void {
    const colourParamMap = {
      I_am_RED: "reds",
      I_am_BLUE: "blues",
      I_am_GREEN: "greens"
    };

    if (field.name === "multiselect_1") {

      const convertedParam = colourParamMap[prop];

      const index = this.filterState[convertedParam].indexOf(value);

      //stops from adding same value again and adds value to array
      if (index === -1) {
        this.filterState[convertedParam].push(value);
      }

    } else {
      //There will be more logic here
      this.filterState[prop] = value;
    }
  }

https://stackblitz.com/edit/ngx-select-dropdown-xkfbyr?file=app%2Fapp.component.ts

【问题讨论】:

  • 我刚刚运行了您的 stackblitz,根据您的最终目标,一切似乎都运行良好:“最终目标:能够从排序数组中添加和删除对象”。我使用了“r”和“red”搜索短语,并且能够成功选择和取消选择项目。我正在使用 Chrome。
  • 不,它们没有被删除。如果您打开控制台 - 从下拉列表中添加一个红色,它会填充红色数组。然后删除您刚刚选择的红色,红色数组仍然填充。

标签: javascript arrays angular typescript ngx-select-dropdown


【解决方案1】:

最后一个简单的解决方法 - 我试图让事情变得过于复杂。我需要重置this.filterState,因为下拉列表中的值将包括之前的每个值,减去被取消选择的值。

  handleFilterChange(prop: string, value: any): void {
    this.filterState = {
      reds: [],
      blues: [],
      greens: []
    };

【讨论】:

    猜你喜欢
    • 2019-05-12
    • 2014-05-26
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多