排序有效,但表中的数据未排序-角度材质表

时间:2020-03-27 19:53:15

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

出于某种原因,表面上的垫子排序会移动箭头,因此排序应该可以,但不能排序...

这是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,
  ],
})

控制台不显示错误消息。箭头出现在排序界面上但表未按应排序的原因是什么?

1 个答案:

答案 0 :(得分:0)

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

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

export class DevizaListComponent implements AfterViewInit {
  ...

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

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

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