0

I am using a mat-table to list the content task . I can also add new comment using dialog panel. After I added a comment and returned back I want my datasource to refresh to show the changes they made.

private update(value: any, id: string): void {
this.dataService.updateCommentaire(id,value)


.subscribe(
    data => {


   this.dataService
  .getTachesByDossierAndSite(this.idDossier, this.idSite)
  .subscribe(
  data => {
    this.taches = data;
    this.dataSource = new MatTableDataSource(this.taches);
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  });
        this.successMessage = "La mise à jour a été effectuée avec succès.";
        this._success.subscribe((message) => this.successMessage = message);
        debounceTime.call(this._success, 5000).subscribe(() => this.successMessage = null);
    }
  );

}

So I have tried to call a refresh method where I get the task from the backend again and then I reinitialize the data source :( any help please to refresh mat-table after add data to datasource!!

a.emma
  • 635
  • 1
  • 6
  • 6
  • what happened when you tried to reinitialize the datasource? any exception?provide more info – Vikas May 07 '18 at 18:27
  • i want to refresh mat-table after add data to datasource without get the task from backend again and reinitialize the data source – a.emma May 08 '18 at 09:31
  • I do not understand your requirements? you want to refresh the table without making an `HTTP` call to backend ? – Vikas May 08 '18 at 11:37
  • could you provide a stackblitz of what have you done so far? – Vikas May 08 '18 at 11:38
  • yes i want to refresh the table without making call to backend – a.emma May 08 '18 at 12:16

2 Answers2

2

You can update your global datasource replacing the data setting with the new data variable.

For example your global variable:

public dataSource: MatTableDataSource<any[]> = new MatTableDataSource([]);

To update its data you just replace data variable:

const data = [...this.dataSource.data];

this.dataService
      .getTachesByDossierAndSite(this.idDossier, this.idSite)
      .subscribe(
        data => {
          this.taches = data;
          this.dataSource.dataSource.data = data;
          this.dataSource.paginator = this.paginator;
          this.dataSource.sort = this.sort;
        });
Sergio Escudero
  • 1,798
  • 14
  • 21
0

One way to refresh data without reloading the whole HTML page is reassigning the data source in one of Angular's lifecycle hooks. In the below code snippet, to display upto date data I'm using the AfterViewChecked hook.

component.ts

ngAfterViewChecked(): void {
  this.lstorage = JSON.parse(localStorage.getItem('employee')!);
  this.dataSource = new MatTableDataSource(this.lstorage);
  this.dataSource.paginator = this.paginator;
  this.dataSource.sort = this.sort;
}
Mahesh More
  • 821
  • 1
  • 8
  • 23
Shekhar
  • 1
  • 2