【问题标题】:Sorting is not working on Material Table in Angular排序不适用于Angular中的材料表
【发布时间】:2021-07-17 21:28:28
【问题描述】:

我正在关注 Angular Material 网站上的基本示例。它以正确的数据显示表格,但排序不起作用。

这里是堆栈闪电战:https://stackblitz.com/edit/angular-jj5qub?file=src%2Fapp%2Ftable-sorting-example.ts

TS 文件

export class TableSortingExample implements OnInit, AfterViewInit {
  ELEMENT_DATA: any;
  dataSource: MatTableDataSource<any>;
  @ViewChild(MatSort) sort: MatSort;

  ngOnInit() {
    this.ELEMENT_DATA = {
      customerHeader: ["ID", "Name", "Address"],
      customerDataRows: [
        ["1", "Mark", "10"],
        ["2", "John", "110"],
        ["3", "John", "110"]
      ]
    };

    this.dataSource = new MatTableDataSource(
      this.ELEMENT_DATA.customerDataRows
    );
  }
  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }
}

HTML 文件

<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
  <ng-container
    *ngFor="let custColumn of ELEMENT_DATA.customerHeader; let colIndex = index"
    matColumnDef="{{ custColumn }}"
  >
    <mat-header-cell *matHeaderCellDef mat-sort-header
      >{{ custColumn }}</mat-header-cell
    >
    <mat-cell *matCellDef="let customerRow">
      {{customerRow[colIndex]}}
    </mat-cell>
  </ng-container>

  <mat-header-row
    *matHeaderRowDef="ELEMENT_DATA.customerHeader; "
  ></mat-header-row>
  <mat-row *matRowDef="let row; columns: ELEMENT_DATA.customerHeader"></mat-row>
</table>

【问题讨论】:

  • 您是否已经在angular material documentation 网站上查看过example 代码?
  • @Igor 是的,如果你看看我的 stackblitz,这有点不同。我也可以在这里添加html

标签: angular typescript angular-material angular-material2


【解决方案1】:

尝试使用键/值对象而不是简单的数组,其信息取决于它们的位置。例如,快速更改您的代码,将您的客户数据数组转换为对象,使您的代码对表格进行排序。

table-sorting-example.ts 中,更改为:

      customerDataRows: [
        ["1", "Mark", "10"],
        ["2", "John", "110"],
        ["3", "John", "110"]
      ]

到:

customerDataRows: [
   { ID: "1", Name: "Mark", Address: "10" },
   { ID: "2", Name: "John", Address: "110" },
   { ID: "3", Name: "John", Address: "110" }
]

table-sorting-example.html 中,从{{customerRow[colIndex]}}{{customerRow[custColumn]}}

P.S.:我喜欢小写的所有键,但只想快速更改代码以显示结果。

查看fork of your project 进行更改。

【讨论】:

  • 抱歉,您不能只更改要求。这不起作用,因为无法更改数据行
猜你喜欢
  • 2022-09-26
  • 1970-01-01
  • 1970-01-01
  • 2015-11-16
  • 2018-12-07
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
相关资源
最近更新 更多