Angular matSort does not sort

后端 未结 8 1749
深忆病人
深忆病人 2020-12-09 03:07

I\'m having trouble with importing matSort into my matTable.

I\'m providing you with my code:

dashboard.component.ts



        
相关标签:
8条回答
  • 2020-12-09 03:22

    I had a similar issue when passing async data from a container layer to the component layer. Here's my solution

    Because the element started off with no data, there's no use to put a constructor or an OnInit as the original example does. Only After the data stream comes in (async) I implement the sort and paginator in a setter, and everything worked perfectly.

    In my template:

    <div class="card">
    
        <div class="card-header">
          <h4>{{pageTitle}}</h4>
          <mat-form-field>
            <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
          </mat-form-field>
        </div>
    
        <div class="card-body p-0">    
          <div class="mat-elevation-z8">
            <table mat-table [dataSource]="dataSource" matSort>
    
              <ng-container matColumnDef="projectNumber">
                <th mat-header-cell *matHeaderCellDef mat-sort-header> Werf Nummer </th>
                <td mat-cell *matCellDef="let row"> W{{row.projectNumber}} </td>
              </ng-container>
    
              <ng-container matColumnDef="description">
                <th mat-header-cell *matHeaderCellDef mat-sort-header> Omschrijving </th>
                <td mat-cell *matCellDef="let row"> {{row.description}} </td>
              </ng-container>
    
              <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
              <tr mat-row *matRowDef="let row; columns: displayedColumns;">
              </tr>
            </table>
    
            <mat-paginator [pageSizeOptions]="[10,20,100]"></mat-paginator>
          </div>      
        </div>
      </div>
    

    In my angular component class i have

        export class ProjectListComponent {
          pageTitle = 'Projects';
          displayedColumns: string[] = ['projectNumber', 'description'];
          dataSource: MatTableDataSource<Project>;
    
          @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
          @ViewChild(MatSort, {static: true}) sort: MatSort;
          @Input() set projects(value: Project[]){
            this.dataSource = new MatTableDataSource(value);
            this.dataSource.paginator = this.paginator;
            this.dataSource.sort = this.sort;
          }
          @Input() selectedProject: Project;
          @Output() selected = new EventEmitter<Project>();
    
          applyFilter(filterValue: string) {
            this.dataSource.filter = filterValue.trim().toLowerCase();
    
            if (this.dataSource.paginator) {
              this.dataSource.paginator.firstPage();
            }
          }
        }
    

    I should mention something else that's really interesting about the filtering option. Note that project here only gets used for two fields but the interface is actually more fields than that, for instance it has an ID. Even though I'm not showing the ID, I can filter by ID with the above code which is pretty awesome.

        export interface Project {
            id: string;
            projectNumber: string;
            description: string;
            activePeriods: ProjectActivePeriod[];
        }
    

    Also note that it's obligated that the matColumnDef="projectNumber" reference in you displayedColumns has to be the exact name of a property in the interface. If I had used 'ProjectNumber', the sort would not work.

    I build this based on the info of

    • example in stackblitz - Data table with sorting, pagination, and filtering.
    • documentation on pagination
    0 讨论(0)
  • 2020-12-09 03:24

    I just had this problem, and all I had to do was making sure you're referencing your matSort viewChild correctly and make sure you have added the MatSortModule in your module.ts file in the imports area.

    Like the following:

    @NgModule({
      imports: [
        MatSortModule,
        MatTableModule,
      ]
    )}
    
    0 讨论(0)
  • 2020-12-09 03:25

    I had the same issue,

    There are a couple of reasons for this issue

    1. Make sure you have included MatSortModule module in your App module
     import { MatSortModule, MatPaginatorModule, MatTableModule } from '@angular/material';
    
     @NgModule({
      imports: [MatSortModule, MatPaginatorModule, MatTableModule],
      exports: []
    })
    
    1. Make sure you have subscribed sort change in the ngAfterViewInit
      ngAfterViewInit() {
        this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0 );
      }
    
    0 讨论(0)
  • 2020-12-09 03:27

    With Angular 8 and Material 6.4.1 if you waiting to receive a data from a service the simplest and best way to fix the MatSort and MatPaginator is to set the static: false instead of true, like this:

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

    In my case is an ngOnChanges call for data.

    0 讨论(0)
  • 2020-12-09 03:29

    So it's happening because of your this.sort.sortChange method is getting called before your child view Initialize

    You Just need to implement your class from AfterViewInit instead of OnInit

    And use ngAfterViewInit life cycle method

    export class ApplicantListComponent implements AfterViewInit {
        @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
        @ViewChild(MatSort, { static: false }) sort: MatSort;
    
        constructor() {}
    
        ngAfterViewInit() {
            this.sort.sortChange.subscribe(() => {
                this.paginator.pageIndex = 0;
                this.paginator.pageSize = this.pageSize;
            });
    } 
    
    0 讨论(0)
  • 2020-12-09 03:30

    I had the same issue and fixed it by adding below:

    @ViewChild(MatSort) set matSort(ms: MatSort) {
    this.sort = ms;
    this.setDataSourceAttributes();
     }
    
    @ViewChild(MatPaginator) set matPaginator(mp: MatPaginator) {
     this.paginator = mp;
    this.setDataSourceAttributes();
     }
    
    setDataSourceAttributes() {
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
      }
    
    0 讨论(0)
提交回复
热议问题