MatSort无法正常工作。我从@ angular / material导入了MatSort模块。 MatSort仅适用于前两行。
<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;
}
答案 0 :(得分:1)
我认为您错过了mat-row
,请尝试以下代码
<强> 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