首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >角7:用MatTableDataSource服务的数据对表进行排序

角7:用MatTableDataSource服务的数据对表进行排序
EN

Stack Overflow用户
提问于 2019-06-24 01:50:44
回答 2查看 1.8K关注 0票数 3

我正在尝试按角7对一个表MatSort进行排序,并且对角进行了新的排序。数据在dataSource中,并正确显示。我的数据来自我为调用后端而创建的服务,然后设置this.dataSource.sort = this.sort,如下面的示例所示:

https://stackblitz.com/angular/qlbmkgjnvya?file=main.ts (来自角度文档!)

我试着跟随角度文档中的例子,但是我觉得我遗漏了一些东西,因为排序对我的示例没有任何作用,但是当我以它们为例并在本地使用它时,它工作得很好。

//构成部分

代码语言:javascript
运行
复制
    import {MatSort} from '@angular/material/sort';
    ...
    dataSource: MatTableDataSource<any[]>;
    @ViewChild(MatSort) sort: MatSort;
    ...
    ngOnInit() {
    this.api.getData().subscribe(data => {
      this.data= data; // this is an array of the data
      this.dataSource = new MatTableDataSource(this.data); // works enough to display on the page without errors
      this.dataSource.sort = this.sort; // has to be in here to ensure no race condition between the api call and setting the sort property
   });

//view (component.html)

代码语言:javascript
运行
复制
<table mat-table #table [dataSource]="dataSource" matSort>

  <!-- Title Column -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> data ID </th>
    <td mat-cell *matCellDef="let element" class="id-col"> {{element.dataID}} </td>
  </ng-container>

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

没有显示错误消息,但表没有更新。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-06-24 02:17:01

如果数据名与列名不匹配,排序函数不知道对哪些数据进行排序,因此它最终什么也不做(?)而不是抛出错误。不知道为什么我不早点想到这个。

票数 1
EN

Stack Overflow用户

发布于 2020-02-12 13:02:29

在更改列以尊重显示列时,我遇到了同样的问题,并解决了这个问题,如下所示:

代码语言:javascript
运行
复制
 displayedColumns: string[] = ['dataID'];

<table mat-table #table [dataSource]="dataSource" matSort>

  <!-- Title Column -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> data ID </th>
    <td mat-cell *matCellDef="let element" class="id-col"> {{element.dataID}} </td>
  </ng-container>

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56729006

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档