Search code examples
angularangular-materialangular-material2ngforangular-material-table

Using *ngFor in reusable components


Can I use an ngFor to change the table data sources? Inside a div run an ngFor which changes the tableData sources rather than explicitly mentioning app data table each time?

Here's the stackbiltz

<div class="container">
  <app-data-table
    [tableData]="tableData1"
    [columnHeader]="columnHeader1"
  ></app-data-table>
  <app-data-table
    [tableData]="tableData2"
    [columnHeader]="columnHeader2"
  ></app-data-table>
</div>

Solution

  • Yes, you can. See https://stackblitz.com/edit/resuable-datatable-nz6xw9

    Change the template to the following:

    <div class="container">
      <ng-container *ngFor="let table of config">
        <app-data-table
          [tableData]="table.data"
          [columnHeader]="table.header"
        ></app-data-table>
      </ng-container>
    </div>
    

    Where the config is:

      config = [
        { data: this.tableData1, header: this.columnHeader1 },
        { data: this.tableData2, header: this.columnHeader2 },
      ];