【问题标题】:How to filter an object array using checkbox with angular?如何使用带角度的复选框过滤对象数组?
【发布时间】:2019-10-20 17:05:40
【问题描述】:

我目前遇到了角度问题。我尝试使用复选框过滤对象数组,但它不起作用。我会尝试按状态过滤我的数组。

当我选中复选框时,我已经尝试使用“ng-true-value”,但由于我的对象数组,它似乎不起作用。


模拟数据.service.ts:

export class MockDataService {
  House: Array<object> = [];

  constructor() {}

  getHouse() {
    let options = {min:100, max:500}
    const types = ["Maison","Appartement","Bureau","Batiment publique"];
    const status = ["En cours","Prêt à publier","Déjà publié","Informations manquantes"];
    // const status = [1,2,3,4,5];
    for (let i = 0; i < 1; i++) {
      const randomTypes = Math.floor(Math.random()*types.length);
      const randomStatus = Math.floor(Math.random()*status.length);
      this.House.push({
        id: faker.random.uuid(),
        owner: faker.company.companyName(),
        username: faker.internet.userName(),
        street: faker.address.streetAddress(),
        city: faker.address.city(),
        garden: faker.random.number(),
        img: faker.image.city(),
        surface: faker.random.number(options),
        title: faker.lorem.word(),
        type: types[randomTypes],
        projectStatus: status[randomStatus],
        date: faker.date.recent(10)
      });
    }

    return of(this.House);
  }

项目列表.component.html:

<input type="checkbox" name="checkbox" [(ngModel)]="checkboxStatus" ng-true-value="'En cours'" ng-false-value="''">
<tr *ngFor="let information of House | filter:searchText | filter:checkboxStatus">

我想要 3 个复选框,当我选中一个复选框时,显示为列表的对象数组应按此复选框进行过滤。

感谢您的帮助!

【问题讨论】:

  • 你能指定复选框是多选还是单选(充当单选按钮)?
  • 请指定是一次过滤一个状态值还是多个值?
  • 您是否使用第三方库进行过滤?还是写了自己的方法?
  • @JoelJoseph 复选框是单选的,我想为我拥有的每个状态设置一个复选框。如果我有“进行中”状态,然后单击“进行中”复选框,它应该只显示具有此状态的项目。
  • @PrashantPimpale 实际上我正在使用 ng2-search-filter 包,但似乎这个包只适用于搜索栏

标签: arrays angular object checkbox filter


【解决方案1】:

您可以通过以下方式做到这一点:


如果你想要单选


something.component.html

    <input type="checkbox" id="ckb" (change)="onCheck($event,'En cours')"  name="En_cours" value="En cours">
    <tr *ngFor="let information of House | search: searchText | filter: filterKey">

something.component.ts

filterKey: string = '';
searchKeyWord: string = '';
onCheck(event,$value){
  if ( event.target.checked ) {
     this.filterKey= $value;
  }
  else
  {
     this.filterKey= '';
  }
}

search.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {

  transform(items: any, term: any): any {
    if (term === undefined) return items;

    return items.filter(function(item) {
      for(let property in item){

        if (item[property] === null){
          continue;
        }
        if(item[property].toString().toLowerCase().includes(term.toString().toLowerCase())){
          return true;
        }

       }
      return false;
    });
  }

}

filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})

export class FilterPipe implements PipeTransform {
  transform(items: any[], filterText: string): any[] {
    if(!items) return [];
    if(!filterText) return items;
filterText = filterText.toLowerCase();
return items.filter( it => {
      return it['projectStatus'].toString().toLowerCase().includes(filterText);
    });
   }

}

如果 Multi-Select 然后对上面的代码做一些改动:


something.component.html

 <input type="checkbox" id="ckb" (change)="onCheck($event,'En cours')"  name="En_cours" value="En cours">
 <tr *ngFor="let information of House | search: searchText | filter: filterKeys">

something.component.ts

filterKeys = [];
searchKeyWord: string = '';
onCheck(event,$value){
  if ( event.target.checked ) {
     this.filterKeys.push($value);
  }
  else
  {
     this.filterKeys.splice(this.filterKeys.indexOf($value), 1);
  }
}

filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})

export class FilterPipe implements PipeTransform {
  transform(array: any[], query:string[]):any[] {
  if (typeof array === 'object') {
   var resultArray = [];
   if (query.length === 0) {
     resultArray = array;
   }
   else {
     resultArray = (array.filter(function (a) {
      return ~this.indexOf(a.projectStatus);
    }, query));
   }
   return resultArray;
 }
 else {
  return null;
  }
 }

}

【讨论】:

  • 检查时出错:ERROR TypeError: "term.toLowerCase is not a function"
  • @StevePiron 更新了答案,请检查。 (对 html、ts 代码和搜索管道的更改)
  • 有人可以解释我如何使用它来进行多选而不是单选吗?我被困住了,我是 Angular 的初学者:/
  • @StevePiron 你只需要稍微改变一下上面的代码filterKeys = []; 然后在检查函数中如果检查然后this.filterKeys.push($value) 否则this.filterKeys.splice(this.filterKeys.indexOf($value), 1); 现在你已经在数组中选择了所有值所以改变相应地过滤管道代码,然后在模板中传递 | filter: filterKeys" 而不是 filterkey
  • 嗯,这就是我为“onCheck”功能考虑的逻辑,谢谢。现在我必须找到管道的解决方案。我想我已经必须修改 filterText 的类型并删除给我一个错误的 toLowerCase 。无论如何,谢谢你的帮助,开始 Angular 是相当乏味的。
猜你喜欢
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 2021-08-18
  • 2019-06-07
  • 2015-08-27
  • 2020-03-06
  • 2019-11-08
  • 2017-08-22
相关资源
最近更新 更多