42

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;
    });
}
2
  • 1
    I think this is correct solution as per Angular Material documentation. If you want to store data into dataSource then you have to use new MatTableDataSource()
    – Tushar
    Sep 3, 2019 at 11:16
  • See my answer on this post stackoverflow.com/questions/54691541/… It is completely possible to use an observable with MatTableDataSource
    – Crash1hd
    Sep 25, 2021 at 19:10

6 Answers 6

48

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;
    });
}
5
  • 2
    Please note that it's quite a bit slower to set the sort after setting data: stackoverflow.com/a/51296374/1596352 (in my own app, it hasn't been quite as extreme as in the link, but still made a noticeable difference.
    – DennisK
    Sep 15, 2020 at 8:54
  • 1
    Yes, i suggest to put the subscription under the ngAfterViewInit function. :D
    – Shan Surat
    Feb 8, 2021 at 8:31
  • 3
    What if I don't want to subscribe to it in the component and use async in the template to get the data? Feb 16, 2021 at 0:54
  • setting paginator and sort MUST be done in ngAfterViewInit
    – JiBi
    Mar 10, 2021 at 11:04
  • How's that the answer to a question on using Observable!?
    – Mr. Gung
    Mar 9 at 11:35
35

Use MatTableDataSource as Observable

You can just pipe your observable:

thingsAsMatTableDataSource$: Observable<MatTableDataSource<Thing>>  =
  getThings().pipe(
    map(things => {
      const dataSource = new MatTableDataSource<Thing>();
      dataSource.data = things;
      return dataSource;
}));

You can use an async pipe on your observable in the template:

[dataSource]="thingsAsMatTableDataSource$ | async"

This way you do not have to subscribe, and can still enjoy mat-table sorting etc...

Prevent Repeated Constructor Calls

Just instantiate it once as a private member and use that instead:

private dataSource = new MatTableDataSource<Thing>();

thingsAsMatTableDataSource$: Observable<MatTableDataSource<Thing>>  =
  getThings().pipe(
    map(things => {
      const dataSource = this.dataSource;
      dataSource.data = things
      return dataSource;
}));

Here's a simple example on Stackblitz.

7
  • 4
    This seems to be the tidiest, safest and most idiomatic approach, and I can confirm that it works. I'm surprised it has so few upvotes. May 17, 2022 at 12:58
  • 6
    Thanks it work but can't use Observable<MatTableDataSource<Thing>> can use Observable<any> Error as below Type 'MatTableDataSource<Service> | null' is not assignable to type 'CdkTableDataSourceInput<Service>'. Sep 17, 2022 at 8:38
  • 1
    I try to use this solution, But getting this error in the HTML file: Type 'MatTableDataSource<Thing> | null' is not assignable to type 'CdkTableDataSourceInput<Thing>'. You know why?
    – levi
    Nov 7, 2022 at 14:16
  • 1
    Same problem here as @PuneetSharma and levi... updating this answer would be great Nov 8, 2022 at 4:24
  • You can either make sure you are always returning the expected object, by returning a default empty source, or just make it of type MatTableDataSource<Thing> | null. But in the second case your template should be able to handle null values.
    – H3AR7B3A7
    Nov 9, 2022 at 20:15
6

this is a workaround, because MatTableDataSource doesn't support Observable as data source

import { MatTableDataSource } from '@angular/material';
import { Observable, Subscription } from 'rxjs';
import { SomeInterface} from './some.interface';

export class CustomDataSource extends MatTableDataSource<SomeInterface> {

    private collection: SomeInterface[] = [];

    private collection$: Subscription;

    constructor(collection: Observable<SomeInterface[]>) {
        super();
        this.collection$ = collection.subscribe(data => {
           this.data = data; // here you have to adjust the behavior as needed
        });
    }

   disconnect() {
     this.collection$.unsubscribe();
     super.disconnect();
   }
}

then in component:

dataSource: CustomDataSource;

ngOnInit(): void {
  const observableData$ = getData();
  this.dataSource = new CustomDataSource(observableData$);
  // this.dataSource.sort = this.sort; // add sorting or filter
}

example: stackblitz

2
  • can you add some explanations to your code ?
    – HDJEMAI
    Mar 10, 2021 at 14:04
  • i made some changes in my post and i added example on stackblitz
    – burasuk
    Mar 12, 2021 at 9:11
3

You can use an observable too, just (*)

[dataSource]="dataSource|async"

(*) really you needn't use the pipe async

See an example in stackblitz, where I replace the first example of the doc by

dataSource = of(ELEMENT_DATA).pipe(delay(1000));
2
  • 1
    But then it is not that easy to use the sorting and pagination features. Sep 3, 2019 at 11:27
  • sorry, you're ok, dataSource can be, a MatTableDataSource, and array or an observable, but you only can sort it if is a MatTableDataSource;
    – Eliseo
    Sep 3, 2019 at 11:35
2

I've released a library for that: @matheo/datasource

I explain the basic concepts in this article:
https://medium.com/@matheo/reactive-datasource-for-angular-1d869b0155f6

and in the example code, you can see how I fetch items from a Firebase database and manipulate the pagination. sorting and filters in the example repo
I hope that you like it and give me your opinion about it ;)

1
  • Your example at Stackblitz doesn't work anymore.
    – Frimlik
    Dec 20, 2022 at 12:25
0

<mat-table [dataSource]="(things$ | async) ?? []">

  things$: Observable<MatTableDataSource<Thing>> =
    this.thingService.getThings().pipe(map(things => new MatTableDataSource<Thing>(things))); ``` 

with this approach async pipe and MatTableDataSource works without error. Sort and pagination can be used afterwards.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.