【问题标题】:Sorting works, but the data in the table is not sorted - Angular Material Table排序工作,但表中的数据未排序 - Angular Material Table
【发布时间】:2020-07-08 14:52:48
【问题描述】:

由于某种原因,表面上垫子的排序有箭头移动,所以排序应该工作,但它没有排序......

这是 HTML:

<div class="mat-elevation-z8">
  <table mat-table [dataSource]="dataSource" matSort>
      <!-- name -->
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>{{ model.fields.name.label }}</th>
        <td mat-cell *matCellDef="let element"> {{ element.name }} </td>
      </ng-container>

   <!-- ... -->
  </table>
</div>

在我的 component.ts 中:

import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';

export class DevizaListComponent implements OnInit {
  dataSource = new MatTableDataSource<DevizaInterface>(devizas);
  devizas: DevizaInterface[] = [
    {
      name: 'dollar',
      code: 'USD' ,
    },
    //...
    //...
  ];
  //...

  @ViewChild(MatSort, { static: true }) sort: MatSort;


  //...

  constructor() { }

  ngOnInit() {
    this.dataSource.sort = this.sort;
  }
}

我在我的 app.module.ts 中导入了这个:

import { MatTableModule } from '@angular/material/table';
import { MatSortModule } from '@angular/material/sort';

@NgModule({
  imports: [
    MatTableModule,
    MatSortModule,
  ],
})

控制台不显示错误消息。排序界面出现箭头,但表格没有按应排序的问题是什么原因?

【问题讨论】:

  • 你能分享一个 jfiddle 的例子吗?

标签: angular typescript angular-material angular-material-table


【解决方案1】:

很可能,当您将this.sort 分配给ngOnInit 内的this.dataSource.sort 时,它还没有定义。因此,dataSource 不接收排序事件。这可能是由于结构指令(即*ngIf)仅在模板中有条件地包含该表。

可以通过更改@ViewChild 上的static 值并在ngAfterViewInit 生命周期挂钩内分配sort 来解决此问题。请参阅有关 component's livecycle 的 Angular 文档。

export class DevizaListComponent implements AfterViewInit {
  ...

  @ViewChild(MatSort, { static: false}) sort: MatSort;

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

您还应该更改类成员的顺序,并在 devizas 初始化后创建 dataSource

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 2021-03-06
    • 2018-03-26
    • 2018-07-25
    • 2018-03-19
    • 2019-08-26
    相关资源
    最近更新 更多