Search code examples
htmlangularnpmangular-materialinterpolation

How to correctly use MatTableExporterModule to export data to excel?


I am using mat-table-exporter npm module within Angular 9 to export mat table components.

I am able to export it correctly with test as the name of the exported file.

Previous working code:

<mat-table matTableExporter [dataSource]="dataSource" #exporter="matTableExporter">

<button mat-raised-button (click)="exporter.exportTable('csv', {fileName:'test',
   Props: {Author: 'myName'}})">
   Export
</button>

I also want to add timestamp in the name of the exported file for which I have written the following code:

New component Code:

exportTable(): void {
  this.exporter.exportTable('csv', {
    filename: `test-${new Date().toISOString()}`,
    Props: { 
      Author: 'myName'
    }
  })
}

New HTML Code:

<mat-table matTableExporter [dataSource]="dataSource" #exporter="matTableExporter">

<button mat-raised-button (click)="exportTable()">Export</button>

The above code is throwing an error:

TS2552: Cannot find name 'exporter'. 

Solution

  • If you want exporter available inside your component, you need to use ViewChild, your html code would stay the same, but the component should change to:

    @ViewChild(MatTableExporterDirective, { static: true }) exporter: MatTableExporterDirective;
    exportIt() {
      this.exporter.exportTable(ExportType.CSV, {
        fileName: "test",
        Props: {
          Author: "myName"
        }
      });
    }