在 Angular 中的嵌套垫 table 中扩展多行不起作用

Expanding multiple rows in a nested mat table in Angular not working

我使用 Angular Material 创建了一个嵌套的 mat-table 网格。但目前一次只能扩展 1 行。我想添加一项功能,以便可以一次展开多行,而不会折叠前一行。

嵌套 Table 的工作 Stackblitz link - https://stackblitz.com/edit/angular-nested-mat-table

尝试将元素推送到 ExpandedElement 数组,但效果不佳 -

const index = this.expandedElements.findIndex(x => x.name == row.name);
if (index === -1) {
  this.expandedElements.push(row);
} else {
  this.expandedElements.splice(index, 1);
}

任何人都可以帮助我如何在其中添加多行扩展吗?

expand/collapse 逻辑与 的答案非常相似。

概念(长话短说;博士)

  1. toggleElement 函数到 添加 elementexpandedElement.
  2. isExpanded 函数 检查 element 是否存在于 expandedElement.
  3. 显示元素(是expanded/collapsed)与isExpanded

解决方案

上一个

<div class="example-element-detail" *ngIf="element.addresses?.data.length" [@detailExpand]="element == expandedElement ? 'expanded' : 'collapsed'">
  <div class="inner-table mat-elevation-z8" *ngIf="expandedElement">
<tr mat-row *matRowDef="let element; columns: columnsToDisplay;" [class.example-element-row]="element.addresses?.data.length"
     [class.example-expanded-row]="expandedElement === element" (click)="toggleRow(element)">
</tr>

由于element被加到expandedElements中表示展开了,所以需要检查元素是否在expandedElementsisExpanded(element).

最新

<div class="example-element-detail" *ngIf="element.addresses?.data.length" [@detailExpand]="isExpanded(element)">
  <div class="inner-table mat-elevation-z8" *ngIf="isExpanded(element)">
<tr mat-row *matRowDef="let element; columns: columnsToDisplay;" [class.example-element-row]="element.addresses?.data.length"
     [class.example-expanded-row]="isExpanded(element)" (click)="toggleRow(element)">
</tr>

.component.ts

export class TableExpandableRowsExample {

  ...

  expandedElements: any[] = [];

  ...

  toggleRow(element: User) {
    element.addresses && (element.addresses as MatTableDataSource<Address>).data.length 
      ? this.toggleElement(element) 
      : null;
    this.cd.detectChanges();
    this.innerTables.forEach((table, index) => (table.dataSource as MatTableDataSource<Address>).sort = this.innerSort.toArray()[index]);
  }

  isExpanded(row: User): string {
    const index = this.expandedElements.findIndex(x => x.name == row.name);
    if (index !== -1) {
      return 'expanded';
    }
    return 'collapsed';
  }

  toggleElement(row: User){
    const index = this.expandedElements.findIndex(x => x.name == row.name);
    if (index === -1) {
      this.expandedElements.push(row);
    } else {
      this.expandedElements.splice(index, 1);
    }
  }
}

Sample Solution on StackBlitz