要禁用 Angular Material MatSort 中的列拖动功能,可以使用 MatSort 的 disableDrag方法。以下是一个代码示例:
HTML 模板:
位置
{{element.position}}
名称
{{element.name}}
重量
{{element.weight}}
TypeScript 代码:
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
export interface Element {
position: number;
name: string;
weight: number;
}
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.scss']
})
export class TableComponent implements OnInit {
displayedColumns: string[] = ['position', 'name', 'weight'];
dataSource: MatTableDataSource;
@ViewChild(MatSort, { static: true }) sort: MatSort;
ngOnInit() {
const elements: Element[] = [
{ position: 1, name: '元素1', weight: 1 },
{ position: 2, name: '元素2', weight: 2 },
{ position: 3, name: '元素3', weight: 3 }
];
this.dataSource = new MatTableDataSource(elements);
this.dataSource.sort = this.sort;
this.disableDragOnSortHeader('position'); // 禁用 'position' 列的拖动功能
}
disableDragOnSortHeader(columnName: string) {
const sortHeader = document.querySelector(`[aria-label="${columnName}"]`) as HTMLElement;
if (sortHeader) {
sortHeader.style.pointerEvents = 'none';
}
}
}
在这个示例中,我们首先使用 MatTableDataSource 创建了一个数据源,并将其与 MatSort 进行绑定。然后,我们调用 disableDragOnSortHeader 方法,将要禁用拖动功能的列名称作为参数传递。该方法会找到对应的排序标头元素,并将其指针事件设置为“none”,从而禁用列的拖动功能。