【问题标题】:Angular 6 filter table with checkboxes带有复选框的Angular 6过滤器表
【发布时间】:2018-12-05 11:35:34
【问题描述】:

I have this working snippet。我想使用复选框过滤表格。问题是,例如,当我检查 a 时,它给了我过滤后的数组。但是当我取消选中它时,我想将原始数组返回给我。

.html

<ng-container *ngFor="let group of groups">
    <label class="btn btn-filter" id="bttns">
    <input type="checkbox" name="customersGroupFilter" autoComplete="off" [value]="group" (change)="changeGroup($event)">
    {{ group }}
  </label>&nbsp;
</ng-container>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Group</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of newArray">
      <td>{{user.name}}</td>
      <td>{{user.group}}</td>
    </tr>
  </tbody>
</table>

.ts

  changeGroup(event) {
    const group = event.target.value;
    const index = this.groupValue.indexOf(group);

    if (index > -1) {
      this.groupValue.splice(index, 1);
    } else {
      this.groupValue.push(group);
    }

    this.transform(this.usersList, 'group', this.groupValue)
  }

  transform(items: any[], field: string, value: string[]): any[] {
    console.log(value)
    if (!items) {
      return [];
    }
    if (!field || !value || value.length <= 0) {
      return items;
    }

    this.newArray = items.filter(singleItem => {
      return (singleItem != null && singleItem[field] != null && singleItem[field] != undefined && value.indexOf(singleItem[field]) >= 0);
    });

    return this.newArray
  }

如何修改此代码以获得我想要的?

我在changeGroup()中尝试了类似这样的条件

if (this.groupValue.length == 0) {
   this.transform(this.usersList, '', this.groupValue)
}

另外,这是过滤表格的好方法吗?我试着避开pipe filters。感谢您的宝贵时间!

【问题讨论】:

  • Java != Javascript ...
  • 哎呀,我的错!我没注意 :D 修改了。

标签: javascript html angular angular6


【解决方案1】:

已更新!!

您正在从原始数组中删除项目,因此您不再拥有数据。

您可以使用不可变的方法,因此使用扩展运算符创建该数组的新版本,然后将其拼接,然后在取消选中复选框时将数组重置为原始值。

originalArray = [1,2,3,4]
newArray = [...array]

然后我会使用newArray 变量和不是原始变量执行 ngFor,这意味着您的表格将对修改后的数组做出反应,但您将始终将 originalArray 作为参考。

下面是transform方法的更新sn-p。

transform(items: any[], field: string, value: string[]): any[] {

    if (!items) {
      return [];
    }

    if (!field || !value || value.length <= 0) {
      return this.newArray = [...this.usersList.slice()];
    }

    this.newArray = items.filter(singleItem => {
      return (singleItem != null && singleItem[field] != null && singleItem[field] != undefined && value.indexOf(singleItem[field]) >= 0);
    });

    return this.newArray
  }
}

【讨论】:

  • 我复制了原始数组,但它不起作用。你能看看我的代码吗?因为我对你的了解不多。
  • 当然让我为你做这些
【解决方案2】:

尝试像这样更改,这应该可以。

...
if (this.groupValue.length == 0) {
  this.transform(this.usersList, '', this.groupValue)
}
...

...
if (!field || !value || value.length <= 0) {
    this.newArray = this.usersList.slice()
    return this.newArray
}
...

【讨论】:

  • 如果我当时使用更多过滤器,它将不再起作用。
猜你喜欢
  • 2019-09-13
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
  • 2019-04-05
  • 1970-01-01
  • 2013-05-20
  • 1970-01-01
  • 2023-04-05
相关资源
最近更新 更多