本文介绍了MatSort 无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MatSort 工作不正常.我从@angular/material 导入了MatSort 模块.MatSort 仅适用于前 2 行.

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;
}

推荐答案

我觉得你缺少mat-row,试试下面的代码

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;
  }
}

工作示例:https://stackblitz.com/edit/angular-qe3bjf-ukzbt2?file=app/table-sorting-example.ts

这篇关于MatSort 无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 20:52