I am using the mat-table and I am trying to use the MatTableDataSource with an observable (I get the data from a web service), but I don't know how to configure the MatTableDataSource to use an observable instead of an array.
Is the only solution to this problem, to subscribe to the observable in the ngOnInit method and always create a new MatTableDataSource when new data arrives?
This is what I have until now, but I don't know if this is the correct solution for working with the MatTableDataSource with an observable.
dataSource: MatTableDataSource<Thing>;
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
@ViewChild(MatSort, { static: true }) sort: MatSort;
ngOnInit() {
getThings().subscribe(things => {
this.dataSource = new MatTableDataSource(things);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
});
}
You should be able to new up the MatTableDataSource
once at the class level and then use the data
setter in ngOnInit
.
dataSource = new MatTableDataSource<Thing>();
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
@ViewChild(MatSort, { static: true }) sort: MatSort;
ngOnInit() {
getThings().subscribe(things => {
this.dataSource.data = things;
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
});
}