Angular + Material - How to refresh a data source (mat-table)

Trigger a change detection by using ChangeDetectorRef in the refresh() method just after receiving the new data, inject ChangeDetectorRef in the constructor and use detectChanges like this:

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { LanguageModel, LANGUAGE_DATA } from '../../../../models/language.model';
import { LanguageAddComponent } from './language-add/language-add.component';
import { AuthService } from '../../../../services/auth.service';
import { LanguageDataSource } from './language-data-source';
import { LevelbarComponent } from '../../../../directives/levelbar/levelbar.component';
import { DataSource } from '@angular/cdk/collections';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { MatSnackBar, MatDialog } from '@angular/material';

  selector: 'app-language',
  templateUrl: './language.component.html',
  styleUrls: ['./language.component.scss']
export class LanguageComponent implements OnInit {
  displayedColumns = ['name', 'native', 'code', 'level'];
  teachDS: any;

  user: any;

  constructor(private authService: AuthService, private dialog: MatDialog,
              private changeDetectorRefs: ChangeDetectorRef) { }

  ngOnInit() {

  add() {, {
      data: { user: this.user },
    }).afterClosed().subscribe(result => {

  refresh() {
    this.authService.getAuthenticatedUser().subscribe((res) => {
      this.user = res;
      this.teachDS = new LanguageDataSource(this.user.profile.languages.teach);

I don't know if the ChangeDetectorRef was required when the question was created, but now this is enough:

import { MatTableDataSource } from '@angular/material/table';

// ...

dataSource = new MatTableDataSource<MyDataType>();

refresh() {
  this.myService.doSomething().subscribe((data: MyDataType[]) => { = data;


So for me, nobody gave the good answer to the problem that i met which is almost the same than @Kay. For me it's about sorting, sorting table does not occur changes in the mat. I purpose this answer since it's the only topic that i find by searching google. I'm using Angular 6.

As said here:

Since the table optimizes for performance, it will not automatically check for changes to the data array. Instead, when objects are added, removed, or moved on the data array, you can trigger an update to the table's rendered rows by calling its renderRows() method.

So you just have to call renderRows() in your refresh() method to make your changes appears.

See here for integration.


Since you are using MatPaginator, you just need to do any change to paginator, this triggers data reload.

Simple trick:


This updates the page size to the current page size, so basically nothing changes, except the private _emitPageEvent() function is called too, triggeing table reload.

Pooja Paigude
this.dataSource = new MatTableDataSource<Element>(this.elements);

Add this line below your action of add or delete the particular row.

refresh() {
  this.authService.getAuthenticatedUser().subscribe((res) => {
    this.user = new MatTableDataSource<Element>(res);   

Best way to do this is by adding an additional observable to your Datasource implementation.

In the connect method you should already be using Observable.merge to subscribe to an array of observables that include the, sort.sortChange, etc. You can add a new subject to this and call next on it when you need to cause a refresh.

something like this:

export class LanguageDataSource extends DataSource<any> {

    recordChange$ = new Subject();

    constructor(private languages) {

    connect(): Observable<any> {

      const changes = [

      return Observable.merge(...changes)
        .switchMap(() => return Observable.of(this.languages));

    disconnect() {
      // No-op

And then you can call recordChange$.next() to initiate a refresh.

Naturally I would wrap the call in a refresh() method and call it off of the datasource instance w/in the component, and other proper techniques.

You can just use the datasource connect function


like so. 'data' being the new values for the datatable

Machhindra Neupane
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';

export class LanguageComponent implemnts OnInit {
  displayedColumns = ['name', 'native', 'code', 'leavel'];
  user: any;
  private update = new Subject<void>();
  update$ = this.update.asObservable();

  constructor(private authService: AuthService, private dialog: MatDialog) {}

   ngOnInit() {
     this.update$.subscribe(() => { this.refresh()});

   setUpdate() {;

   add() {, {
     data: { user: this.user },
   }).afterClosed().subscribe(result => {

 refresh() {
   this.authService.getAuthenticatedUser().subscribe((res) => {
     this.user = res;
     this.teachDS = new LanguageDataSource(this.user.profile.languages.teach);   

in my case (Angular 6+), I inherited from MatTableDataSource to create MyDataSource. Without calling after = someArray as T[])

data where not displayed

class MyDataSource

export class MyDataSource<T extends WhateverYouWant> extends MatTableDataSource<T> {

    private entitiesSubject = new BehaviorSubject<T[]>([]);

    loadDataSourceData(someArray: T[]){ = someArray //whenever it comes from an API asyncronously or not as T[])// Otherwise data not displayed

    public connect(): BehaviorSubject<T[]> {
        return this.entitiesSubject

}//end Class 

You can easily update the data of the table using "concat":

for example:


teachDS: any[] = [];


<table mat-table [dataSource]="teachDS" class="list">

And, when you update the data (language.component.ts):

addItem() {
    // newItem is the object added to the list using a form or other way
    this.teachDS = this.teachDS.concat([newItem]);

When you're using "concat" angular detect the changes of the object (this.teachDS) and you don't need to use another thing.

PD: It's work for me in angular 6 and 7, I didn't try another version.

Cristian Hernandez

This worked for me:

refreshTableSorce() {
    this.dataSource = new MatTableDataSource<Element>(this.newSource);

I think the MatTableDataSource object is some way linked with the data array that you pass to MatTableDataSource constructor.

For instance:

dataTable: string[];
tableDS: MatTableDataSource<string>;

   // here your pass dataTable to the dataSource
   this.tableDS = new MatTableDataSource(this.dataTable); 

So, when you have to change data; change on the original list dataTable and then reflect the change on the table by call _updateChangeSubscription() method on tableDS.

For instance:


That's work with me through Angular 6.

Tiny King

This is working for me:

dataSource = new MatTableDataSource<Dict>([]);
    public search() {
        let url = `${Constants.API.COMMON}/dicts?page=${}&` + 
        ( == '' ? '' : `name_like=${}`);
    this._http.get<Dict>(url).subscribe((data)=> {
    // this.dataSource = data['_embedded'].dicts; =  data['_embedded'].dicts; = data['page'];

So you should declare your datasource instance as MatTableDataSource

I did some more research and found this place to give me what I needed - feels clean and relates to update data when refreshed from server:

Most credits to the page above. Below is a sample of how a mat-selector can be used to update a mat-table bound to a datasource on change of selection. I am using Angular 7. Sorry for being extensive, trying to be complete but concise - I have ripped out as many non-needed parts as possible. With this hoping to help someone else getting forward faster!


export class Organization {
    id: number;
    name: String;


import { Observable, empty } from 'rxjs';
import { of } from 'rxjs';

import { Organization } from './organization.model';

export class OrganizationService {
  getConstantOrganizations(filter: String): Observable<Organization[]> {
    if (filter === "All") {
      let Organizations: Organization[] = [
        { id: 1234, name: 'Some data' }
      return of(Organizations);
     } else {
       let Organizations: Organization[] = [
         { id: 5678, name: 'Some other data' }
     return of(Organizations);

  // ...just a sample, other filterings would go here - and of course data instead fetched from server.


import { CollectionViewer, DataSource } from '@angular/cdk/collections';
import { Observable, BehaviorSubject, of } from 'rxjs';
import { catchError, finalize } from "rxjs/operators";

import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';

export class OrganizationDataSource extends DataSource<Organization> {
  private organizationsSubject = new BehaviorSubject<Organization[]>([]);

  private loadingSubject = new BehaviorSubject<boolean>(false);

  public loading$ = this.loadingSubject.asObservable();

  constructor(private organizationService: OrganizationService, ) {

  loadOrganizations(filter: String) {;

    return this.organizationService.getOrganizations(filter).pipe(
      catchError(() => of([])),
      finalize(() =>
    ).subscribe(organization =>;

  connect(collectionViewer: CollectionViewer): Observable<Organization[]> {
    return this.organizationsSubject.asObservable();

  disconnect(collectionViewer: CollectionViewer): void {


<div class="spinner-container" *ngIf="organizationDataSource.loading$ | async">

  <form [formGroup]="formGroup">
    <mat-form-field fxAuto>
      <div fxLayout="row">
        <mat-select formControlName="organizationSelectionControl" (selectionChange)="updateOrganizationSelection()">
          <mat-option *ngFor="let organizationSelectionAlternative of organizationSelectionAlternatives"

<mat-table fxLayout="column" [dataSource]="organizationDataSource">
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
    <mat-cell *matCellDef="let organization">{{}}</mat-cell>

  <ng-container matColumnDef="number">
    <mat-header-cell *matHeaderCellDef>Number</mat-header-cell>
    <mat-cell *matCellDef="let organization">{{organization.number}}</mat-cell>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>


.spinner-container {
    height: 360px;
    width: 390px;
    position: fixed;


import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs';

import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';
import { OrganizationDataSource } from './organizationdatasource.model';

  selector: 'organizations',
  templateUrl: './organizations.component.html',
  styleUrls: ['./organizations.component.scss']
export class OrganizationsComponent implements OnInit {
  public displayedColumns: string[];
  public organizationDataSource: OrganizationDataSource;
  public formGroup: FormGroup;

  public organizationSelectionAlternatives = [{
    id: 1,
    name: 'All'
  }, {
    id: 2,
    name: 'With organization update requests'
  }, {
    id: 3,
    name: 'With contact update requests'
  }, {
    id: 4,
    name: 'With order requests'

    private formBuilder: FormBuilder,
    private organizationService: OrganizationService) { }

  ngOnInit() {
    this.formGroup ={
      'organizationSelectionControl': []

    const toSelect = this.organizationSelectionAlternatives.find(c => == 1);

    this.organizationDataSource = new OrganizationDataSource(this.organizationService);
    this.displayedColumns = ['name', 'number' ];

  updateOrganizationSelection() {

After reading Material Table not updating post data update #11638 Bug Report I found the best (read, the easiest solution) was as suggested by the final commentor 'shhdharmen' with a suggestion to use an EventEmitter.

This involves a few simple changes to the generated datasource class

ie) add a new private variable to your datasource class

import { EventEmitter } from '@angular/core';
private tableDataUpdated = new EventEmitter<any>();

and where I push new data to the internal array (, I emit an event.

public addRow(row:myRowInterface) {;

and finally, change the 'dataMutation' array in the 'connect' method - as follows

const dataMutations = [

// this is the dataSource
this.guests = [];

this.guests.push({id: 1, name: 'Ricardo'});

// refresh the dataSource this.guests = Array.from(this.guest);

npm install @matheo/datasource

I released a library aimed to be the official Material DataSource in the future, supporting any kind of input streams (sort, pagination, filters), and some configuration with debugging to see how it works while you're coding.

import { MatDataSourceModule } from '@matheo/datasource';

You can find the StackBlitz demo and further information here:

I'd be glad to hear your opinion and support your use cases if necessary.
Happy coding!

I achieved a good solution using two resources:

refreshing both dataSource and paginator: = this.users;

where for example dataSource is defined here:

    users: User[];
    dataSource = new MatTableDataSource(this.users);
    this.dataSource.paginator = this.paginator;

well, i ran into a similar problem where i add somthing to the data source and it's not reloading the easiest way i found whas simply to re assing the data

let dataSource = ['a','b','c']
let cloned = dataSource.slice()
// OR IN ES6 // let cloned = [...dataSource]
dataSource = cloned