Angular <mat-table>:如何禁用指定列的排序表头?
如何在mat-table中禁用指定列的排序表头
当然可以,你有两种简单方式实现需求,和使用<table mat-table>还是<mat-table>无关——后者只是写法不同,本质上同样能给列配置排序:
方法1:直接移除该列的mat-sort-header指令
如果某列完全不需要排序功能,也不需要显示排序相关的表头样式,直接不给对应的<mat-header-cell>添加mat-sort-header指令即可:
<mat-table [dataSource]="dataSource" matSort> <!-- 可排序的列 --> <ng-container matColumnDef="name"> <mat-header-cell *matHeaderCellDef mat-sort-header> 名称 </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell> </ng-container> <!-- 禁用排序的列:不添加mat-sort-header --> <ng-container matColumnDef="id"> <mat-header-cell *matHeaderCellDef> ID </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.id}} </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table>
方法2:保留表头样式但禁用排序功能
如果希望该列表头和其他排序列保持一致的样式,但点击不会触发排序,可以给mat-sort-header添加[disableSorting]="true"输入属性:
<ng-container matColumnDef="status"> <mat-header-cell *matHeaderCellDef mat-sort-header [disableSorting]="true"> 状态 </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.status}} </mat-cell> </ng-container>
补充说明:你之前觉得<mat-table>无法给列指定mat-sort-header是误解——在<mat-table>的结构中,每个列定义(matColumnDef)对应的<mat-header-cell>完全可以添加mat-sort-header指令,用法和<table mat-table>里的表头单元格一致,只是前者用ng-container包裹列的定义逻辑而已。
内容的提问来源于stack exchange,提问作者Valentino Ru
相关产品推荐
相关产品推荐

