繁体   English   中英

Angular 中的物料表无法进行排序

[英]Sorting is not working on Material Table in Angular

我正在关注 angular 材料网站上的基本示例。 它显示具有正确数据的表,但排序不起作用。

这是堆栈闪电战: 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>

尝试使用键/值对象而不是简单的 arrays,其信息取决于其 position。 例如,快速更改代码以转换对象中的客户数据 arrays 使您的代码对表进行排序。

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]}}

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

查看包含更改的项目的分支

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM