Angular Material Table基于dataSource对象数组属性大小的rowspan列

Bar*_*rni 10 angular-material angular

即使现在在Angular Material的7.2版本中,我似乎找不到关于如何在mat-table上使用rowspan并保留组件功能的示例.

这是多远(简短?)我得到的:

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

上面的Stackblitz中的示例"几乎"是我正在寻找的,但我无法看到如何完成它.

...
===============================================
||     ||            ||            ||  row1  ||
||  1  ||  Hydrogen  ||   1.0079   ||========||
||     ||            ||            ||  row2  ||
===============================================
||     ||            ||            ||  row1  ||
||     ||            ||            ||========||
||  2  ||   Helium   ||   4.0026   ||  row2  ||
||     ||            ||            ||========||
||     ||            ||            ||  row3  ||
===============================================
||     ||            ||            ||  row1  ||
||  3  ||  Lithium   ||   6.941    ||========||
||     ||            ||            ||  row2  ||
===============================================
...
Run Code Online (Sandbox Code Playgroud)

使用其他元数据格式的示例可在以下位置找到:

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

在我的Stackblitz(第一个链接)之后,我的问题是:

我是否实现了这个rowpan shim/hack?

如何根据行['description']大小的长度循环行?

如果我在对象中有另一个数组属性怎么办?我可以迭代并生成其大小的列/行/ rowspan,这样会变得更通用吗?

我正在努力为社区找到一个通用的解决方案.

Jus*_*ode 8

好吧,似乎材料表没有用于它的api文档,我也找不到任何技巧可以做到这一点,但是我们可以选择数据以支持此操作,如您的第二个示例所示,我们可以将数据重新构造为新的json和我们可以获得预期的结果。

步骤1 :

    const originalData = [
      { id: 1, name: 'Hydrogen', weight: 1.0079, descriptions: ['row1', 'row2'] },
      { id: 2, name: 'Helium', weight: 4.0026, descriptions: ['row1', 'row2', 'row3'] },
      { id: 3, name: 'Lithium', weight: 6.941, descriptions: ['row1', 'row2'] },
      { id: 4, name: 'Beryllium', weight: 9.0122, descriptions: ['row1', 'row2', 'row3'] },
      { id: 5, name: 'Boron', weight: 10.811, descriptions: ['row1'] },
      { id: 6, name: 'Carbon', weight: 12.0107, descriptions: ['row1', 'row2', 'row3'] },
      { id: 7, name: 'Nitrogen', weight: 14.0067, descriptions: ['row1'] },
      { id: 8, name: 'Oxygen', weight: 15.9994, descriptions: ['row1'] },
      { id: 9, name: 'Fluorine', weight: 18.9984, descriptions: ['row1', 'row2', 'row3'] },
      { id: 10, name: 'Neon', weight: 20.1797, descriptions: ['row1', 'row2', 'row3'] },
    ]; //original data

    const DATA = originalData.reduce((current, next) => {
      next.descriptions.forEach(b => {
        current.push({ id: next.id, name: next.name, weight: next.weight, descriptions: b })
      });
      return current;
    }, []);//iterating over each one and adding as the description 
    console.log(DATA)

    const ELEMENT_DATA: PeriodicElement[] = DATA; //adding data to the element data
Run Code Online (Sandbox Code Playgroud)

第2步

这将是您的第二个stackblitz链接。

 getRowSpan(col, index) {    
    return this.spans[index] && this.spans[index][col];
  }
Run Code Online (Sandbox Code Playgroud)

第三步

因为它是你的第二个链接

  constructor() {
    this.cacheSpan('Priority', d => d.id);
    this.cacheSpan('Name', d => d.name);
    this.cacheSpan('Weight', d => d.weight);
  }

  /**
   * Evaluated and store an evaluation of the rowspan for each row.
   * The key determines the column it affects, and the accessor determines the
   * value that should be checked for spanning.
   */
  cacheSpan(key, accessor) {
    for (let i = 0; i < DATA.length;) {
      let currentValue = accessor(DATA[i]);
      let count = 1;

      // Iterate through the remaining rows to see how many match
      // the current value as retrieved through the accessor.
      for (let j = i + 1; j < DATA.length; j++) {
        if (currentValue != accessor(DATA[j])) {
          break;
        }

        count++;
      }

      if (!this.spans[i]) {
        this.spans[i] = {};
      }

      // Store the number of similar values that were found (the span)
      // and skip i to the next unique row.
      this.spans[i][key] = count;
      i += count;
    }
  }
Run Code Online (Sandbox Code Playgroud)

第四步

使用索引向下传递到rowpan并隐藏不需要的行

    <ng-container matColumnDef="id">
        <th mat-header-cell *matHeaderCellDef> Priority </th>
        <td mat-cell *matCellDef="let data;let i = dataIndex" [attr.rowspan]="getRowSpan('Priority',i)" [style.display]="getRowSpan('Priority', i) ? '' : 'none'">
         {{ data.id }} </td>
    </ng-container>

    <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef> Name </th>
        <td mat-cell *matCellDef="let data;let i = dataIndex" [attr.rowspan]="getRowSpan('Name',i)" [style.display]="getRowSpan('Name', i) ? '' : 'none'">
         {{ data.name }} </td>
    </ng-container>

    <ng-container matColumnDef="weight">
        <th mat-header-cell *matHeaderCellDef> Weight </th>
        <td mat-cell *matCellDef="let data;let i = dataIndex" [attr.rowspan]="getRowSpan('Weight',i)" [style.display]="getRowSpan('Weight', i) ? '' : 'none'">
         {{ data.weight }} </td>
    </ng-container>

    <ng-container matColumnDef="descriptions">
        <th mat-header-cell *matHeaderCellDef> Descriptions </th>
        <td mat-cell *matCellDef="let data"> {{ data.descriptions }} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> 


</table>
Run Code Online (Sandbox Code Playgroud)

这是演示


Kyl*_*yle 6

因为我对所提供的答案不满意(尤其是cacheSpan实施方面)。

我想出了一些更方便的恕我直言,就像这样:

export class TableBasicExample {
  displayedColumns = ['priority', 'status', 'dateCreated', 'testNumber', 'testCurrency', 'testTime'];
  dataSource = DATA;

  spans = {};

  constructor() {
    this.spans = Object.assign({}, {
      priority: this.spanDeep(['priority'], DATA),
      status: this.spanDeep(['priority', 'status'], DATA),
      dateCreated: this.spanDeep(['priority', 'status', 'dateCreated'], DATA)
    });
  }

  spanDeep(paths: string[] | null, data: any[]) {
    if (!paths.length) {
      return [...data]
        .fill(0)
        .fill(data.length, 0, 1);
    }

    const copyPaths = [...paths];
    const path = copyPaths.shift();

    const uniq = uniqWith(data, (a, b) => get(a, path) === get(b, path))
      .map(item => get(item, path));

    return uniq
      .map(uniqItem => this.spanDeep(copyPaths, data.filter(item => uniqItem === get(item, path))))
      .flat(paths.length);
  }

  getRowSpan(path, idx) {
    return this.spans[path][idx];
  }
};
Run Code Online (Sandbox Code Playgroud)

工作示例可以在这里找到:https://stackblitz.com/edit/angular-lnahlh-hw2d3b


小智 1

我们必须说出有多少行,但有些行具有相同的行id,如果它们使用相同的 id,我们将对 td 进行排序和合并。但是对于您的数据,据说那里有一些行,并且描述是数组并且可以拆分。这样JS就无法知道<tr>应该有多少个。

有 2 种方法供您使用: 1- 格式化数据,每行保留一个描述,与第二个 href 中的示例数据相同,[{id, name, weight, countdescriptions, description},...],并[attr.rowspan]='data.countdescriptions'改为使用[attr.rowspan]='getRowSpan(data.id)'。2-更新内容格式,如<ul><li *ngFor...描述中所示<td>,并删除[attr.rowspan]属性。