Search code examples
angularloopsngformat-table

ngFor in Angular Material Table nested datasource


I have datasource with nested arrays and can`t find the way to iterate them with mat-table

my datasource = [
   {
    group: {id: 1, name: name1},
    products: [
      {id:1, 
       name: prodName1,
       price: price1
      },

      {id:2, 
       name: prodName2,
       price: price2
      }
    ] 
   },


   {
    group: {id: 2, name: name2},
    products: [
      {id:1, 
       name: prodName1,
       price: price1
      },

      {id:2, 
       name: prodName2,
       price: price2
      }
    ] 
   }
]

I need table like this:

group    product     price
---------------------------------
group1   prodName1   price1

group1   prodName2   price2

group2   prodName1   price1

group2   prodName2   price2

I found examples only with nested rows and common cell for group1, group2. Is it possible to iterate products for each group using angular material table?


Solution

  • No there is no way to directly iterate through the inner group.

    To achieve the your requirement you just have to made another array having such data.

    For that, just use the following code to manipulate the data.

    let dataForTable=[];
     dataSource.forEach((group)=>{
      group.forEach(product)=>{
     dataForTable.push({group:group.name,product:product.name,price:product.price})   
    }}