Angular 具有列值的物料表数据源筛选器

Angular 具有列值的物料表数据源筛选器,angular,typescript,angular-material,Angular,Typescript,Angular Material,如何筛选具有特定列的物料数据表 public dataSource; this.dataSource = new MatTableDataSource(this.items); this.dataSource.filterPredicate = function customFilter(data , filter:string ): boolean { return (data.name.startsWith(filter)); }

如何筛选具有特定列的物料数据表

public dataSource;


this.dataSource = new MatTableDataSource(this.items);
        this.dataSource.filterPredicate = function customFilter(data , filter:string ): boolean {
            return (data.name.startsWith(filter));
        }

applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
}

当我键入返回的数据不匹配时,上述代码不起作用

来自文档

例如,数据对象{id:123,名称:'Mr.Smith',favoriteColor:'blue'}将减少为123mr。史密斯蓝。如果筛选字符串为蓝色,则会将其视为匹配,因为它包含在简化字符串中,并且该行将显示在表中

要覆盖默认筛选行为,请使用自定义筛选预测 可以设置函数,该函数接受数据对象和筛选器字符串,并 如果数据对象被视为匹配项,则返回true

如果只想使用特定列筛选,则需要覆盖
filterPredicate
,答案已经是

这是过滤的工作示例

表格过滤示例.html

<div class="example-container mat-elevation-z8">
  <div class="example-header">
    <mat-form-field>
      <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
    </mat-form-field>
  </div>

  <mat-table #table [dataSource]="dataSource">

    <!-- Position Column -->
    <ng-container matColumnDef="position">
      <mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.position}} </mat-cell>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
    </ng-container>

    <!-- Weight Column -->
    <ng-container matColumnDef="weight">
      <mat-header-cell *matHeaderCellDef> Weight </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.weight}} </mat-cell>
    </ng-container>

    <!-- Symbol Column -->
    <ng-container matColumnDef="symbol">
      <mat-header-cell *matHeaderCellDef> Symbol </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.symbol}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>
</div>

您可以使用filterPredicate筛选特定列,如下所示:

  ngOnInit() {
    this.dataSource.filterPredicate = (data: Element, filter: string) => {
      return data.name == filter;
     };
   }
 applyFilter(filterValue: string) {
    // filterValue = filterValue.trim(); // Remove whitespace
    // filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

我更改了
applyFilter()
并添加了
ngOnInit()
。现在它只工作于名称列和完全相同的值
(==)

您可以通过动态列进行筛选,如无硬编码列名称,执行以下操作:

//在输入焦点上:设置filterPredicate以仅按输入列进行筛选
setupFilter(列:字符串){
this.dataSource.filterPredicate=(d:TableDataSourceType,filter:string)=>{
const textToSearch=d[column]&&d[column].toLowerCase()| |“”;
返回textToSearch.indexOf(filter)!=-1;
};
}
applyFilter(filterValue:string){
this.dataSource.filter=filterValue.trim().toLowerCase();
}
在模板中,可以有如下内容:

  ngOnInit() {
    this.dataSource.filterPredicate = (data: Element, filter: string) => {
      return data.name == filter;
     };
   }
 applyFilter(filterValue: string) {
    // filterValue = filterValue.trim(); // Remove whitespace
    // filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

或者更复杂的示例,使用每列筛选动态创建标题行:


请注意,不能有多个具有相同键的标题行,因此这将不起作用:


您可以利用它进行复杂的筛选

为了筛选列,您需要定义一个示例实体,并仅填充属于相应列的属性


下面是一个示例:

使用filterPredicate为物料表创建自定义筛选选择框,以使用customFilter()方法覆盖

演示

来源

app.compont.html


不
{{element.position}
名称
{{element.name}
重量
{{element.weight}}
象征
{{element.symbol}
app.component.ts

从'@angular/core'导入{Component,OnInit,ViewChild};
从'@angular/material/paginator'导入{MatPaginator};
从“@angular/material/table”导入{MatTableDataSource};
从'@angular/material/sort'导入{MatSort};
导出接口周期元素{
名称:字符串;
职位:编号;
重量:个数;
符号:字符串;
}
常量元素_数据:PeriodiceElement[]=[
{位置:1,名称:'Hydrogen',重量:1.0079,符号:'H'},
{位置:2,名称:'氦',重量:4.0026,符号:'他'},
{位置:3,名称:'锂',重量:6.941,符号:'锂'},
{位置:4,名称:'铍',重量:9.0122,符号:'铍'},
{位置:5,名称:'硼',重量:10.811,符号:'B'},
{位置:6,名称:'Carbon',重量:12.0107,符号:'C'},
{位置:7,名称:'N',重量:14.0067,符号:'N'},
{位置:8,名称:'氧气',重量:15.9994,符号:'O'},
{位置:9,名称:'氟',重量:18.9984,符号:'F'},
{位置:10,名称:'Neon',重量:20.1797,符号:'Ne'},
];
@组成部分({
选择器:'app mat table',
templateUrl:'./mat table.component.html',
样式URL:['./mat table.component.css'],
})
导出类MatTableComponent{
displayedColumns:string[]=['position','name','weight','symbol'];
数据源=新MatTableDataSource(元素数据);
@ViewChild(MatPaginator,{static:true})paginator:MatPaginator;
@ViewChild(MatSort,{static:true})sort:MatSort;
恩戈尼尼特(){
this.dataSource.paginator=this.paginator;
this.dataSource.sort=this.sort;
}
applyFilter(filterValue:string){
this.dataSource.filter=filterValue.trim().toLowerCase();
}
}

尝试使用mat输入、mat图标和多标题行的单列过滤器


您应用了筛选器吗?@David Ya我已经应用了筛选器。我需要使用特定列进行筛选。请检查答案。我已经添加了特定的列过滤器答案,并检查它是否正常工作@bereketgebredinglewhat如果我想导出excel工作簿中的过滤数据。因此,我可以将数据导出到excel,但我想将数据限制为通过自定义谓词过滤掉的数据。请提供帮助,以及如何在此解决方案中应用多个过滤器?在TypeScription中的另一个字段之间进行过滤为什么这不是公认的答案?在本例中,它非常直接地解释了。。!!
        ...
        ngOnInit() {
            this.getRemoteData();

            // Overrride default filter behaviour of Material Datatable
            this.dataSource.filterPredicate = this.createFilter();
        }
        ...

        // Custom filter method fot Angular Material Datatable
        createFilter() {
            let filterFunction = function (data: any, filter: string): boolean {
            let searchTerms = JSON.parse(filter);
            let isFilterSet = false;
            for (const col in searchTerms) {
                if (searchTerms[col].toString() !== '') {
                isFilterSet = true;
                } else {
                delete searchTerms[col];
                }
            }

            let nameSearch = () => {
                let found = false;
                if (isFilterSet) {
                for (const col in searchTerms) {
                    searchTerms[col].trim().toLowerCase().split(' ').forEach(word => {
                    if (data[col].toString().toLowerCase().indexOf(word) != -1 && isFilterSet) {
                        found = true
                    }
                    });
                }
                return found
                } else {
                return true;
                }
            }
            return nameSearch()
            }
            return filterFunction
        }
applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    if (filterValue == '') {
        this.tablesource = this.filteresource;
    }
    else if (filterValue != '') {
        this.tablesource = this.filteresource.filter(e =>
            e.galleryDesc.toLowerCase().includes(filterValue.trim().toLowerCase()) ||
            e.galleryName.toLowerCase().includes(filterValue.trim().toLowerCase()) ||
            e.status.toString().toLowerCase().includes(filterValue.trim().toLowerCase()) ||
            e.createdDate.toLowerCase().includes(filterValue.trim().toLowerCase())
      );
    }
}
 <mat-form-field floatPlaceholder="never">
            <input matInput placeholder="Filter name" (keyup)="applyFilter($event.target.value)">
          </mat-form-field>
        <mat-table matSort  [dataSource]="dataSource" class="mat-elevation-z8">
           
            <!-- Position Column -->
            <ng-container matColumnDef="position">
              <mat-header-cell *matHeaderCellDef mat-sort-header> No. </mat-header-cell>
              <mat-cell *matCellDef="let element"> {{element.position}} </mat-cell>
            </ng-container>
          
            <!-- Name Column -->
            <ng-container matColumnDef="name">
              <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
              <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
            </ng-container>
          
            <!-- Weight Column -->
            <ng-container matColumnDef="weight">
              <mat-header-cell *matHeaderCellDef mat-sort-header> Weight </mat-header-cell>
              <mat-cell *matCellDef="let element"> {{element.weight}} </mat-cell>
            </ng-container>
          
            <!-- Symbol Column -->
            <ng-container matColumnDef="symbol">
              <mat-header-cell *matHeaderCellDef mat-sort-header> Symbol </mat-header-cell>
              <mat-cell *matCellDef="let element"> {{element.symbol}} </mat-cell>
            </ng-container>
          
            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
          </mat-table>
          <mat-paginator [pageSize]="5" [pageSizeOptions]="[5, 10, 15]" showFirstLastButtons></mat-paginator>
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
  { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
  { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
  { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
  { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
  { position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
  { position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
  { position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' },
  { position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
  { position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
];

@Component({
  selector: 'app-mat-table',
  templateUrl: './mat-table.component.html',
  styleUrls: ['./mat-table.component.css'],
})
export class MatTableComponent {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);

  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: true }) sort: MatSort;

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }
  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}