首页 > 解决方案 > Angular2数据表过滤列

问题描述

如何使用 Angular2 数据表过滤整个列(标题和数据)?

我能够过滤列数据,但标题仍然存在..:

https://stackblitz.com/edit/data-table-filter-columns

编辑:

这实际上很容易,也是我的疏忽。解决方案只是将我的过滤功能添加到 matHeaderRowDef 以及 matRowDef。我已经更新了我的 stackblitz,所以它现在可以按我的预期工作

标签: angulardatatableangular-material

解决方案


我只给你一个例子作为解决方案,因为它并不难,你可以在docs中找到解决方案。只需将这种情况应用于您的情况。

尝试类似文档中的方法,因此将显示的数据分离为表格的列、行和通用数据。

const ELEMENT_DATA: PeriodicElement[] = [
    {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
    {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
];
data: PeriodicElement[] = ELEMENT_DATA;

displayedColumns: string[] = ['name', 'weight', 'symbol', 'position'];

columnsToDisplay: string[] = this.displayedColumns.slice(); //returns a copy of displayedColumns

现在您可以在 html 文件中使用它们,如下所示:

<table mat-table [dataSource]="data">
    <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
        <th mat-header-cell *matHeaderCellDef> {{column}} </th>
        <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
    </ng-container>

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

作为您的解决方案的示例,我将在 html 文件中添加一个按钮以触发删除最后一列:(在某种程度上与排序相同)

<button mat-raised-button (click)="removeColumn()"> Remove column </button>

现在我们只需要删除数组的最后一个元素即可删除displayedColumns表的最后一列。

removeColumn() {
    this.columnsToDisplay.pop(); //removes the last element of the array
}

推荐阅读