Angular Material Table Sort

把之前做的 Table 加上 sort 功能 參考資料 https://material.angular.io/components/table/overview

基本設定

1. 引入必要的模組

@Component({
  selector: 'app-prac-mrt',
  standalone: true,
  imports: [CommonModule, MatTableModule, MatSortModule],
  templateUrl: './prac-mrt.component.html',
  styleUrl: './prac-mrt.component.css',
})

2. 定義介面和資料

interface StationData {
  Station: string;
  Destination: string;
  UpdateTime: string;
}

const ELEMENT_DATA: StationData[] = StationList;

3. Component 中的設定

export class PracMrtComponent {
  // 定義要顯示的欄位
  displayedColumns: string[] = ['Station', 'Destination', 'UpdateTime'];
  
  // 建立資料來源
  dataSource = new MatTableDataSource(ELEMENT_DATA);

  // 使用 ViewChild 取得 sort 參考
  @ViewChild(MatSort) sort!: MatSort;

  // 在視圖初始化後設定 sort
  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }
}

HTML 模板設定

1. Table 基本結構

<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">

2. 欄位定義

<!-- Station 欄位 -->
<ng-container matColumnDef="Station">
  <th mat-header-cell *matHeaderCellDef mat-sort-header>Station</th>
  <td mat-cell *matCellDef="let element">{{ element.Station }}</td>
</ng-container>

<!-- 其他欄位類似... -->

3. 表頭和資料列定義

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

關鍵點說明

  1. @ViewChild 的作用

    • 用於獲取模板中 MatSort 指令的參考

    • 必須使用 ! 運算符告訴 TypeScript 這個屬性一定會被賦值

    @ViewChild(MatSort) sort!: MatSort;
  2. ngAfterViewInit 的重要性

    • 是設定 sort 的正確時機點

    • 在此時 @ViewChild 已經獲取到 sort 參考

    ngAfterViewInit() {
      this.dataSource.sort = this.sort;
    }
  3. 模板中的必要屬性

    • matSort:加在 table 元素上

    • mat-sort-header:加在需要排序的欄位的表頭上

可選功能:排序變更通知

可以加入排序變更時的通知功能:

private _liveAnnouncer = inject(LiveAnnouncer);

announceSortChange(sortState: Sort) {
  if (sortState.direction) {
    this._liveAnnouncer.announce(`Sorted ${sortState.direction}ending`);
  } else {
    this._liveAnnouncer.announce('Sorting cleared');
  }
}
<table mat-table [dataSource]="dataSource" matSort (matSortChange)="announceSortChange($event)">

注意事項

  1. 排序功能支持所有資料類型,包括中文字串

  2. 確保在 ngAfterViewInit 中設定 sort,而不是在其他生命週期鉤子中

  3. 每個需要排序的欄位都要加上 mat-sort-header

Last updated