Home > OS >  Angular 14 - Creating multiple mat-tables dynamically from JSON
Angular 14 - Creating multiple mat-tables dynamically from JSON

Time:01-19

I'm looking to essentially loop through a JSON that would look like this

  [
    {
      "name": "TESTING",
      "steps": [
        {
          "i": "35%",
          "ii": "65%",
        }
      ]
    },
    {
      "name": "TESTING",
      "steps": [
        {
          "i": "35%",
          "ii": "65%",
        }
      ]
    }
  ]

Then from this json I would create a table with "TESTING" as the first row, and the steps and their respective numbers i, ii....

So something like this,

 TESTING
i      35%

My first thought was to use a *ngFor on a table so like <table *ngFor="let object of json"> but then how would I dynamically attach a dataSource to each table?

If this seems pointless, I agree, I'm looking for better ways to present this data but this is what has to be done as of right now.

CodePudding user response:

There are a few different routes you could take to implement such a pattern.

One that may work nicely would be to leverage ngTemplateOutlet & ngTemplateOutletContext directives to 'scaffold-out' the mat tables in a template, and pass the data as context... something similar to this approach to get your started:

@Component({
  selector: 'app-table-component',
  template: `
    <div>
      <ng-container
        [ngTemplateOutlet]="tmpl"
        [ngTemplateOutletContext]="ctx">
      </ng-container>
        <!-- Your table structure insice this template   -->
      <template #tmpl let-name let-location="location">
        {{ name }} : {{ location }}
      </template>
    </div>
  `
})
export class TableComponent {
  ctx = {
    name: 'This is a test',
    location: 'Some location'
  };
}

You could imagine using this component to define a single table, and then iteratively define app-table-components in a loop, passing the ctx data as inputs.

CodePudding user response:

The mat-table data source can be an array of object (the problem is that we can not sort or paginate so easy)

<mat-table *ngFor="let object of json" [dataSource]="object.steps">
</mat-table>

If we need give a MatTableDataSource there no problem. We create the mat-tables and in ngAfterViewInit, get the mat-tables using ViewChildren and give value to the MatDatasources

<!--see that we don't give dataSource-->
<mat-table *ngFor="let object of json" >
</mat-table>

  @ViewChildren(MatTable) tables:QueryList<MatTable<any>>
  ngAfterViewInit(){
   this.tables.forEach((x:MatTable<any>,index:number)=>{
     x.dataSource=new MatTableDataSource(this.json[index].items)
   })
  }

A simple stackblitz

  • Related