How can I create an Angular Material Design table with infinite columns, for known number of rows?

后端 未结 1 458
囚心锁ツ
囚心锁ツ 2021-01-28 23:12

I have created an HTML table which will generate infinite columns based on the number of rows in the input data. I\'ve tried to use this SO p

1条回答
  •  不思量自难忘°
    2021-01-28 23:44

    the only thing you need is "loop" the matColumnDef. -see that we use [matColumnDef] and {{element[col]}}

    If your table is like

    
        
    {{col}} {{element[col]}}

    You only need transform your data and indicate the displayedColumns. You can do in a ngOnInit()

    ngOnInit() {
        const head = this.data.map(x => x.name)
        const data: any[] = [];
        this.data.forEach((x, index) => {
          Object.keys(x).forEach((k, index2) => {
            data[index2] = data[index2] || {}
            data[index2][head[index]] = x[k]
    
          })
        })
        this.displayedColumns=head;
        this.dataSource = data.slice(1); //I remove the first element that was the "header"
      } 
    

    See in stackblitz

    0 讨论(0)
提交回复
热议问题