matSort headers not sorting table at all

2019-08-18 03:31发布

问题:

  • Live Demo: https://matsort-audionote.firebaseapp.com/ (click the "title" header)
  • My code: https://github.com/AskYous/audio-note/commit/75c667f66ec4e15a5dbd460ec044938782d672a4

I'm having a difficult time getting sortable headers to work. I attached a live demo of my app having header sorting not working, as well as the code I used to implement this. When I click on a header, I get not response. No errors, no sorting, no feedback. I did the following:

  1. Added matSort directive to the table.
  2. Added mat-sort-header to each header.
  3. Imported MatSortModule into app.module.ts.
  4. Provided the MatSort directive to the table data source.

The headers are clickable, and they have toggling arrows, but the rows are not being sorted on click.

回答1:

It is because you are initializing your datasource's sort as matSort before table is rendered in DOM (because of the *ngIf)

this.notes.sort = this.sort;

change this line

<table mat-table [dataSource]="notes" *ngIf="notes.data" matSort>

to

<table mat-table [dataSource]="notes" [hidden]="!notes.data" matSort>