【发布时间】:2022-01-07 09:57:30
【问题描述】:
谁能告诉我如何将mat-sort-header 功能从标题中提取到菜单中。
当我单击一个标题时,我想打开一个菜单。在这个菜单中,我想使用matSort 功能。
其实我是想触发matSortChange 事件
【问题讨论】:
标签: angular angular-material mat-table
谁能告诉我如何将mat-sort-header 功能从标题中提取到菜单中。
当我单击一个标题时,我想打开一个菜单。在这个菜单中,我想使用matSort 功能。
其实我是想触发matSortChange 事件
【问题讨论】:
标签: angular angular-material mat-table
您在询问“上下文菜单”和“管理垫排序”。这是一个广泛的问题,我真的不知道如何回答,所以一个简短的数据
如果您看到source of matSort。您可以“覆盖”方法排序。
你可以使用一些类似的
@ViewChild(MatSort) sort: MatSort;
ngAfterViewInit(){
this.sort.sort=(sortable: MatSortable)=>{
//this only to update the variables active and direction
if (this.sort.active != sortable.id) {
this.sort.active = sortable.id;
this.sort.direction = sortable.start ? sortable.start : this.sort.start;
} else {
this.sort.direction = this.sort.getNextSortDirection(sortable);
}
//this make the table sorted
this.sort.sortChange.emit({active: this.sort.active, direction: this.sort.direction});
}
this.dataSource.sort = this.sort;
}
因此您可以选择“不发出更改”或在上下文菜单中发出。
对于上下文菜单,您可以使用 cdk-overlay。它没有很好的记录,但如果你想要一个例子,前段时间我写了这个SO。
另一种选择是标题的每个 td 都是一个 mat-menu
注意:我不知道您在 Angular 方面的知识有多少,所以这个答案可能对您没有太大帮助。给我们更多数据
更新好吧,我们已经拥有了这些数据所需的一切,所以继续吧!
首先,我们“重写”排序函数什么都不做,并创建一个新函数来进行排序
ngOnInit()
{
this.sort.sort=(sortable: MatSortable)=>null
this.dataSource.sort=this.sort
}
sortTable(active:string,direction:string)
{
this.sort.active=active
this.sort.direction=direction as SortDirection
this.sort.sortChange.emit({active: active, direction: direction as SortDirection});
}
然后在 th 中使用 mat-menu。所以我们的 th 会是这样的
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef (click)="positionTrigger.openMenu()">
<span mat-button [matMenuTriggerFor]="position" #positionTrigger="matMenuTrigger">No.</span>
<mat-menu #position="matMenu">
<button mat-menu-item (click)="sortTable('position','asc')">
<mat-icon
*ngIf="sort.active=='position' && sort.direction=='asc'"
>checked</mat-icon
><span>Ascend</span>
</button>
<button mat-menu-item (click)="sortTable('position','desc')">
<mat-icon
*ngIf="sort.active=='position' && sort.direction=='desc'"
>checked</mat-icon
><span>Descend</span>
</button>
</mat-menu>
</th>
<td mat-cell *matCellDef="let element">{{element.position}}</td>
</ng-container>
最后,我们需要一些 .css 来“移除”材质添加的箭头。 在styles.css中
.custom-table .mat-sort-header-arrow
{
visibility:collapse;
min-width: 0;
}
为了美化我们在 component.css 中的菜单
button.mat-menu-item
{
height: 1.75rem!important;
font-size:12px;
text-overflow: unset;
display:flex;
align-items: center;
justify-content: flex-start;
}
button.mat-menu-item >span
{
padding-right: 24px;
padding-left:24px;
}
button.mat-menu-item .mat-icon+span
{
padding-left:0;
}
.mat-menu-item .mat-icon
{
font-size:12px;
height:1.75rem!important;
margin-right: 0;
margin-top:1rem;
}
this stackblitz中的结果
【讨论】: