如何使用Angular Material的复选框过滤数据源?

时间:2019-10-20 17:32:12

标签: html angular typescript angular-material

我正在尝试通过单击filter my datatablecheckbox。选中一个复选框可以正确过滤它,但是checking multipleproblem

Angular Material documentation对于涉及许多元素的正确过滤非常含糊。它与filterPredicate有关,但是几乎没有(或者非常模糊)在线文档。

<mat-form-field appearance="legacy">
              <mat-label>Select Province(s)</mat-label>
              <mat-select placeholder='Provinces' formControlName="provinceSelector" multiple>
                <mat-option *ngFor="let p of provinces" [value]='p.provinceName' (click)='addfilter()'>
                  {{p.provinceName}} ({{p.adsInProvince}})
                </mat-option>
              </mat-select>
            </mat-form-field>

this.registeredUserService.GetAllAdverts().subscribe(val => {

      this.dataSource = new MatTableDataSource<Card>(val);
      this.dataSource.paginator = this.paginator;
const myPredicate = (myObject:IProvince,filterString:any)=>
      {
        let filterObj:IProvince = JSON.parse(filterString);
        if(!filterObj.provinceName.includes((obj)=>obj=myObject.provinceName))
        {
          return false;
        }
        else
        {return true;}
      }
      this.dataSource.filterPredicate=myPredicate;

myFilter:IProvince={
    provinceName:[]
  }
  addfilter() {
    this.myFilter.provinceName=this.search.value;
    this.dataSource.filter = JSON.stringify(this.myFilter);
  }

export interface Card {
  advertDate: any;
  advertDescription: any;
  advertID: any;
  cityName: any;
  provinceName: any;
  sellerID: any;
  sellingPrice: any;
  vehicleColor: any;
  vehicleMake: any;
  vehicleMileage: any;
  vehicleModel: any;
  vehicleYear: any;
}
export interface IProvince{
  provinceName:any[];
}

它应该只过滤选定的值...

操作不正确。

1 个答案:

答案 0 :(得分:0)

您对过滤谓词的看法是正确的。您可以定义如何过滤数据源。该函数返回true(如果过滤器匹配)或false。

const myPredicate = (myObject, filterString) => {
  let filterObj: MyFilterObj = JSON.parse(filterString);
  if(!filterObj.attributeA.find((obj) => obj == myObject.name) ||myObject.attributeB != filterObject.attributeB) { // <-- edit includes to find
    return false;
  } else {
    return true;
  }
}

在生成MatTableDataSource之后输入以下代码:

this.dataSource.filterPredicate = this.myPredicate.

使用以下方法设置过滤器。我总是提供一个类型字符串来确定我要设置的过滤器。

myFilter: MyFilterObject = {   // <-- define this variable in your ngOnInit method
  attributeA: [], // <-- this is the place where you can put your selected options
  attributeB: null
}

applyFilter(value: any, type: string) {
  switch(type) {
    case "attributeA":
       this.myFilter.attributeA = value;
       break;
     case "attributeB":
       this.myFilter.attributeB = value;
       break;
     default:
       break;
  }
  this.dataSource.filter = JSON.stringify(this.myFilter);
}