📜  mat-sort 在动态生成的表中不起作用 - TypeScript (1)

📅  最后修改于: 2023-12-03 14:44:10.036000             🧑  作者: Mango

mat-sort in dynamically generated table not working - TypeScript

When dynamically generating a table in Angular using MatSort, it is possible to face the issue where the sorting functionality of MatSort is not working as expected. This is because when the table is generated dynamically, the sorting service is not properly initialized, resulting in an inability to sort any columns.

To solve this issue, one solution is to manually initialize the sorting service after the table is created. This can be done using the AfterViewInit lifecycle hook.

Here is an example implementation:

import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';

export interface TableData {
  name: string;
  age: number;
}

@Component({
  selector: 'app-table',
  template: `
    <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
        <td mat-cell *matCellDef="let element"> {{element.name}} </td>
      </ng-container>
      <ng-container matColumnDef="age">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Age </th>
        <td mat-cell *matCellDef="let element"> {{element.age}} </td>
      </ng-container>
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>
  `,
  styleUrls: ['./table.component.scss'],
})
export class TableComponent implements AfterViewInit {
  @ViewChild(MatSort) sort: MatSort;

  displayedColumns: string[] = ['name', 'age'];
  dataSource: MatTableDataSource<TableData>;

  ngAfterViewInit(): void {
    this.dataSource.sort = this.sort;
  }

  constructor() {
    this.dataSource = new MatTableDataSource<TableData>([
      { name: 'John', age: 30 },
      { name: 'Jane', age: 25 },
      { name: 'Bob', age: 40 },
      { name: 'Doe', age: 50 },
    ]);
  }
}

In this implementation, the MatSort directive is added to the header cells of each column. Additionally, the sort property of the MatTableDataSource is set to the MatSort instance after the view has been initialized using the ngAfterViewInit lifecycle hook.

By manually initializing the sorting service in this way, the sorting functionality of MatSort should work as expected in a dynamically generated table.