0

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

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

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

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

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

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

这是我放在一起的堆栈闪电战......

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

4

1 回答 1

0

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

  handleFilterChange(prop: string, value: any): void {
    this.filterState = {
      reds: [],
      blues: [],
      greens: []
    };
于 2021-03-08T17:31:53.167 回答