Home > other >  Using *ngFor in reusable components
Using *ngFor in reusable components

Time:06-23

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 >
  <app-data-table
    [tableData]="tableData1"
    [columnHeader]="columnHeader1"
  ></app-data-table>
  <app-data-table
    [tableData]="tableData2"
    [columnHeader]="columnHeader2"
  ></app-data-table>
</div>

CodePudding user response:

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

Change the template to the following:

<div >
  <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 },
  ];

CodePudding user response:

Of course you can. Just create an array of the data/header objects you want to consume.

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

You can call the fields on these objects anything you want, but a descriptive name will make the bindings in your template more clear.

Then use the ngFor structural directive to iterate through the array you just created. Bind the [tableData] and [columnHeader] attributes of the app-data-table to the fields on the iteration object.

<div >
  <app-data-table *ngFor="let table of tables"
    [tableData]="table.data"
    [columnHeader]="table.header">
  </app-data-table>
</div>
  • Related