【问题标题】:Material table datasource filter with column value具有列值的材料表数据源过滤器
【发布时间】:2018-10-20 06:04:14
【问题描述】:

如何过滤具有特定列的材料数据表?

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;
}

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

【问题讨论】:

  • 您是否应用了过滤器?
  • @David Ya 我已经应用了过滤器。

标签: angular typescript angular-material


【解决方案1】:

来自文档。

例如数据对象{id: 123, name: 'Mr. Smith', favoriteColor: 'blue'} 将减少到 123mr。史密斯布鲁。如果您的过滤器字符串是蓝色的,那么它将被视为匹配,因为它包含在缩减的字符串中,并且该行将显示在表格中。

要覆盖默认过滤行为,自定义 filterPredicate 可以设置函数,它接受一个数据对象和过滤器字符串, 如果数据对象被认为是匹配的,则返回 true。

如果您只想过滤特定列,您需要覆盖filterPredicate,答案已经是here

这是过滤的工作示例。

table-filtering-example.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>

table-filtering-example.ts

  import {Component} from '@angular/core';
    import {MatTableDataSource} from '@angular/material';

    /**
     * @title Table with filtering
     */
    @Component({
      selector: 'table-filtering-example',
      styleUrls: ['table-filtering-example.css'],
      templateUrl: 'table-filtering-example.html',
    })
    export class TableFilteringExample {
      displayedColumns = ['position', 'name', 'weight', 'symbol'];
      dataSource = new MatTableDataSource(ELEMENT_DATA);

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

    export interface Element {
      name: string;
      position: number;
      weight: number;
      symbol: string;
    }

    const ELEMENT_DATA: Element[] = [
      {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'},
      {position: 11, name: 'Sodium', weight: 22.9897, symbol: 'Na'},
      {position: 12, name: 'Magnesium', weight: 24.305, symbol: 'Mg'},
      {position: 13, name: 'Aluminum', weight: 26.9815, symbol: 'Al'},
      {position: 14, name: 'Silicon', weight: 28.0855, symbol: 'Si'},
      {position: 15, name: 'Phosphorus', weight: 30.9738, symbol: 'P'},
      {position: 16, name: 'Sulfur', weight: 32.065, symbol: 'S'},
      {position: 17, name: 'Chlorine', weight: 35.453, symbol: 'Cl'},
      {position: 18, name: 'Argon', weight: 39.948, symbol: 'Ar'},
      {position: 19, name: 'Potassium', weight: 39.0983, symbol: 'K'},
      {position: 20, name: 'Calcium', weight: 40.078, symbol: 'Ca'}, ];

您可以使用 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()。现在它只工作 name 列和完全相同的值(==)

【讨论】:

  • 我需要使用特定列进行过滤。
  • 请检查答案。我添加了特定的列过滤器答案并检查它是否正常工作。 @bereketgebredingle
  • 如果我想将过滤后的数据导出到 Excel 工作簿中。所以我可以将数据导出到 excel,但我想将数据限制为被我们的自定义谓词过滤掉的数据。请帮忙
【解决方案2】:

您可以利用mat-table-filter 进行复杂的过滤。

为了过滤列,您定义一个示例实体并仅填充属于相应列的属性。

这里是一个例子:https://stackblitz.com/github/HalitTalha/mat-table-filter-example

【讨论】:

  • 为什么这不是公认的答案,在这个例子中解释得非常直截了当..!!
【解决方案3】:

您可以按动态列进行过滤,如没有硬编码的列名,执行以下操作:

// On input focus: setup filterPredicate to only filter by input column
setupFilter(column: string) {
  this.dataSource.filterPredicate = (d: TableDataSourceType, filter: string) => {
    const textToSearch = d[column] && d[column].toLowerCase() || '';
    return textToSearch.indexOf(filter) !== -1;
  };
}

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

在模板中你可以有这样的东西:

<ng-container matColumnDef="item-filter">
  <th mat-header-cell *matHeaderCellDef>
    <input (keyup)="applyFilter($event.target.value)" (focus)="setupFilter('name')" />
  </th>
</ng-container>

或者更复杂的例子,动态创建带有逐列过滤的标题行:

<table mat-table [dataSource]="dataSource">
   <ng-container *ngFor="let filterCol of ['names', 'age', 'address']">
     <ng-container matColumnDef="filterCol">
       <th mat-header-cell *matHeaderCellDef>
         <input (keyup)="applyFilter($event.target.value)" (focus)="setupFilter(filterCol)"/>
       </th>
     </ng-container>
   </ng-container>

   <tr mat-header-row *matHeaderRowDef="['names', 'age', 'address']"></tr>
</table>

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

<tr mat-header-row *matHeaderRowDef="['names', 'age', 'address']"></tr>
<tr mat-header-row *matHeaderRowDef="['names', 'age', 'address']"></tr>

【讨论】:

  • 以及如何使用此解决方案应用多个过滤器?
【解决方案4】:

使用 filterPredicate 为 Material 表创建自定义过滤器选择框,用 customFilter() 方法覆盖

演示Link

来源Link

        ...
        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
        }

【讨论】:

    【解决方案5】:

    app.compont.html

     <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>
    

    app.component.ts

    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();
      }
    }
    

    【讨论】:

      【解决方案6】:
      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())
            );
          }
      }
      

      【讨论】:

      • 在打字稿中的另一个字段之间过滤
      【解决方案7】:

      使用 mat-input、mat-icon 和多标题行尝试这个单内联过滤器 https://angular-material-table-multiple-header-rows-hyfefz.stackblitz.io/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-19
        • 1970-01-01
        • 2019-03-14
        • 1970-01-01
        • 2020-12-28
        • 1970-01-01
        相关资源
        最近更新 更多