I have a data coming from an endpoint and put it into MatTableDataSource. I was able to get it working for MatSort and MatPaginator, but needed to use setTimeOut, which does not seems to be a proper way to do this. If I remove this, it will complain that 'Can not read property of sort undefined' which I assumed this is due to it's not initialized yet.
I also have tried:
- to move moving it to afterviewinit, but the data was loaded after afterviewinit getting called so it still does not work
- using this.changeDetectorRef.detectChanges() after this.datasource = new ... also does not work
This is my current code (which is working, but using settimeout)
<div *ngIf="!isLoading">
<div *ngFor="let record of renderedData | async" matSort>
// ... some html to show the 'record'
<mat-paginator #paginator
[pageSizeOptions]="[5, 10, 20]">
</mat-paginator>
</div>
The Component
export class ResultsComponent implements OnInit, OnDestroy, AfterViewInit {
dataSource: MatTableDataSource<any> = new MatTableDataSource();
renderedData: Observable<any>;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
constructor(some service) {}
ngOnInit() {
const accountId = someOtherService.getAccountId();
this.someService.getData(accountId)
.subscribe((myData) => {
this.dataSource = new MatTableDataSource(myData);
// it won't work properly if it is not wrapped in timeout
setTimeout(() => {
this.dataSource.paginator = this.paginator;
this.sort.sort(<MatSortable>({id: 'created_on', start: 'desc'}));
this.dataSource.sort = this.sort;
});
this.renderedData = this.dataSource.connect();
}
});
}
ngAfterViewInit() {
}
ngOnDestroy(): void {
if (this.dataSource) { this.dataSource.disconnect(); }
}
}
The above code is working for me, I'm just looking the right way not to use settimeout if possible.
ChangeDetectorRef.detecChanges()
afterthis.dataSource = ...
, instead of usingsetTimeout
. – ConnorsFandetectChanges
runs the full check of current view and all children, it's a very expensive way, and emptysetTimeout
doesn't look like evil comparing to this way IMHO – Commercial Suicide