I have this table which I'm using for multiple datas.
My issue is that the data is displayed correctly, but paginator and sort are not working.
Sort only shows the arrows, but won't sort
Paginator won't count the items and will display "0 of 0"
Here is my code: component.html
<mat-table class="lmat-elevation-z8" [dataSource]="dataSources[pagePart]" matSort>
<ng-container *ngFor="let column of columns[pagePart]" [matColumnDef]="column.columnDef">
<mat-header-cell *matHeaderCellDef mat-sort-header>{{ column.header }}</mat-header-cell>
<mat-cell *matCellDef="let row">{{ row[column.columnDef] }}</mat-cell>
</ng-container>
<ng-container matColumnDef="azioni">
<mat-header-cell *matHeaderCellDef>Azioni</mat-header-cell>
<mat-cell *matCellDef="let row">
<button>... here there's a list of action buttons for each row ...</button>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns[pagePart].concat('azioni'); sticky:true"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns[pagePart].concat('azioni')"></mat-row>
</mat-table>
And my code to load the data is: component.ts
displayedColumns={};
columns={};
dataSources={};
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
loadPart(part){
this.http.get("myapi").subscribe(data=>{
// load data
var datas=[];
for(var k=0; k<data["length"]; ++k){
datas.push(data[k]);
}
// setup columns
this.columns[part]=[];
this.displayedColumns[part]=[];
if(data["length"]>0) // setup column names, headers and everything
for(var key in data[0]){
if(key.indexOf("id")>=0) continue;
this.displayedColumns[part].push(key);
this.columns[part].push({
columnDef: key,
header: this.renameHeader(key) // rename header based on the name provided by the api
});
}
// setup table
this.dataSources[part]=new MatTableDataSource(datas);
// load all the possible shit
this.dataSources[part].sort = this.sort;
this.dataSources[part].paginator = this.paginator;
// apply changes
this.data_loaded[part]=true;
this.cdr.detectChanges();
});
}
Any ideas on how to make paginator and sort work?
Ok, turns out the problem was in the @ViewChild declaration.
In my component init I have:
@Component({
selector: 'm-profile',
templateUrl: './profile.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
Which then requires to ChangeDetectorRef.detectChanges()
in order to update the DOM
Which prevents the ViewChild from assigning the correct references, so once the ViewChild I need is actually visible (in the beginning they're wrapped in a *ngIF
) I just reassign dataSource.paginator=this.paginator
and then re-detectChanges()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With