Reputation: 51
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;
}
Upvotes: 0
Views: 3490
Reputation: 6050
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
Upvotes: 1