MatSort is not working properly

走远了吗. 提交于 2019-12-23 05:09:08

问题


MatSort is not working properly. I have imported the MatSort module from @angular/material. MatSort is working only for first 2 rows.

<mat-table [dataSource]="dataSource" matSort>
    <ng-container matColumnDef="slno">
      <mat-header-cell *matHeaderCellDef mat-sort-header> SL NO. </mat-header-cell>
      <mat-cell *matCellDef="let row; let i = index"> {{i+1}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="project">
       <mat-header-cell *matHeaderCellDef mat-sort-header> PROJECT</mat-header-cell>
       <mat-cell *matCellDef="let row"> {{row.project_name}}</mat-cell>
    </ng-container>

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

TS:

@Component({
  selector: 'project',
  templateUrl: './project.component.html',
  styleUrls: ['./project.component.css']
})
export class ProjectComponent implements OnInit {
  displayedColumns = ['slno', 'project', 'startdate', 'enddate', 'action'];
  @ViewChild(MatSort) sort: MatSort;
ngOnInit() {
  //get data
  this.dataSource = new MatTableDataSource(data);
  this.dataSource.paginator = this.paginator;
     this.dataSource.sort = this.sort;
}

回答1:


I think you are missing the mat-row, try the below code

HTML:

<mat-table #table [dataSource]="dataSource" matSort>
    <ng-container matColumnDef="slno">
      <mat-header-cell *matHeaderCellDef mat-sort-header> SL NO. </mat-header-cell>
      <mat-cell *matCellDef="let row; let i = index"> {{i+1}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="project">
       <mat-header-cell *matHeaderCellDef mat-sort-header> PROJECT</mat-header-cell>
       <mat-cell *matCellDef="let row"> {{row.project_name}}</mat-cell>
    </ng-container>

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

TS:

@Component({
  selector: 'table-sorting-example',
  styleUrls: ['table-sorting-example.css'],
  templateUrl: 'table-sorting-example.html',
})
export class TableSortingExample {
  displayedColumns = ['slno', 'project'];

 //this will be your projects data
  dataSource = new MatTableDataSource(ELEMENT_DATA);

  @ViewChild(MatSort) sort: MatSort;

  /**
   * Set the sort after the view init since this component will
   * be able to query its view for the initialized sort.
   */
  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }
}

Working example: https://stackblitz.com/edit/angular-qe3bjf-ukzbt2?file=app/table-sorting-example.ts



来源:https://stackoverflow.com/questions/49533125/matsort-is-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!