Search code examples
angularangular-materialmat-table

Angular material table collapse/expand complete table so only header is visible


I got many material tables on my page, to make browsing easier I would like to make a complete table collapse/expand when clicking on the header (or a small button inside the header). I find many examples on how to expand table rows but I need to collapse the complete table.


Solution

  • Solution:

    When tapping collapse, I assign an empty array to the data source of that table. when clicking expands I reassign the original array to the data source of that table. This way my header&footer cells which contain totals for the table are still visible but the inner cells are not.

    Something like the code below should allow this behavior:

    collapse(index: number) {
    if (this.contracts[index].tabledatasource.data.length == 0) {
      this.contracts[index].tabledatasource = new MatTableDataSource(this.stockArray[index]);
    } else {
      this.contracts[index].tabledatasource = new MatTableDataSource([]);
    }
    
    
    }