代码之家  ›  专栏  ›  技术社区  ›  A T

来自`{foo:{bar:5,can:6},haz:{bar:7,can:8}}`的垫子桌?

  •  0
  • A T  · 技术社区  · 6 年前

    目标:

    -------------------
    |     | foo | haz |
    -------------------
    | bar | 5   | 7   |
    | can | 6   | 8   |
    -------------------
    

    <ng-container matColumnDef="score">
        <th mat-header-cell *matHeaderCellDef> Score </th>
        <td mat-cell *matCellDef="let user"> {{user.score}} </td>
    </ng-container>
    

    我在这里遗漏了什么,难道没有简单的方法从输入中构造一个材料表吗?

    0 回复  |  直到 6 年前
        1
  •  1
  •   uminder    6 年前

    这可以使用 Object.keys() Object.reduce() 通过下面的代码。

    private baseData = {
      foo: {bar: 5, can: 6}, 
      haz: {bar: 7, can: 8}
    };
    
    columnNames: string[]; 
    data: any[];  
    
    ngOnInit() {
      this.columnNames = [' '].concat(Object.keys(this.baseData));
      const objects = Object.keys(this.baseData).map(key => this.baseData[key]);
      this.data = Object.keys(objects[0]).reduce((acc, k) => {
        const entry = { ' ' : k };
        objects.forEach((o, i) => entry[this.columnNames[i + 1]] = o[k]);
        acc.push(entry);
        return acc;
      }, []);    
    }
    

    请看一下以下内容 StackBlitz .

        2
  •  0
  •   Richard Schibly    6 年前

    下面是mat table的基本示例的修改stackblitz:

    https://stackblitz.com/edit/angular-cj5c3w

    您不能在mat表上使用数组作为数据源,但这应该可以满足您的需要。你得检查副作用和边缘病例。

    推荐文章