MatTable在分页和排序时展开折叠图标问题

时间:2018-12-14 08:11:11

标签: angular typescript angular-material2 angular-material-6 angular-material-table

我有一个角形材料表,该表使用detailRow指令将明细/同级相邻行插入到表行中。

StackBlitz

我想给它一个外观,好像该行正在扩展或折叠一样,因此我向其中添加了几个图标,单击包含它们的单元格可以切换它们。

<mat-header-cell *matHeaderCellDef> Action </mat-header-cell>
      <mat-cell *matCellDef="let element"> 
         <button mat-icon-button color="primary"  (click)="element[i] = !element[i]">
            <mat-icon id="expand_more"  #expand_more *ngIf="!element[i] "  >expand_more</mat-icon>
            <mat-icon id="expand_less"  #expand_less *ngIf="element[i] ">expand_less</mat-icon>
          </button> 
      </mat-cell>

但是,如果我让该行保持展开和分页状态或进行某种排序,则图标不会切换,因为无法切换它们。

我尝试加入page事件或sortChange事件,但是空了。

我知道,有一种新方法可以在角形材质v7中进行扩展/折叠,这可能与分页和排序效果很好,但是在我升级之前还需要一段时间,与此同时,有人对如何进行扩展有任何想法。解决这个问题。

1 个答案:

答案 0 :(得分:1)

简短回答

cdk-detail-row.directive.ts 中添加此

  ngOnDestroy(): void {
    this.row[undefined] = false;
  }

长期回答

首先,您要在mat-row中捕获2个位置的单击,而在mat-cell中捕获另一个(单击该图标会触发两个事件。单击该行上的其他位置只会触发onToggleChange)。而且,此element[i] = !element[i]是一个骇客-(变量i未定义)。因此,如果单击该行中的其他任何位置,展开图标都不会更改,这就是为什么我感到困惑的原因,因为我认为这不应该更改。该示例将使点击Mat-cell变得简单。

table-basic-example.html 中,您应该从中删除(单击)输出,并将row参数添加到onToggleChange($ event,row)方法中。并更改* ng-if来代替element.close

<ng-container matColumnDef="expandCollapse">
  <mat-header-cell *matHeaderCellDef> Action </mat-header-cell>
  <mat-cell *matCellDef="let element"> 
     <button mat-icon-button color="primary">
        <mat-icon id="expand_more"  #expand_more *ngIf="!element.close"  >expand_more</mat-icon>
        <mat-icon id="expand_less"  #expand_less *ngIf="element.close">expand_less</mat-icon>
      </button> 
  </mat-cell>
</ng-container>

<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"
        class="element-row"
        [cdkDetailRow]="row" [cdkDetailRowTpl]="tpl"
        (toggleChange)="onToggleChange($event, row)">
</mat-row>

table-basic-example.ts

将close属性添加到界面元素

export interface Element {
    name: string;
    position: number;
    weight: number;
    symbol: string;
    close?: boolean;
}

现在,我们将在onToggleChange方法中处理行的关闭和打开。

onToggleChange(cdkDetailRow: CdkDetailRowDirective, row: Element): void {
    if (this.singleChildRowDetail && this.openedRow && this.openedRow.expended) {
        this.openedRow.toggle();
    }
    if (!row.close) {
        row.close = true;
    } else {
        row.close = false;
    }
    this.openedRow = cdkDetailRow.expended ? cdkDetailRow : undefined;
}

最后,在 cdk-detail-row.directive.ts 中,一旦该指令因分页或切换而被破坏,我们将要关闭该行。因此,我们将实现onDestroy方法

export class CdkDetailRowDirective implements OnDestroy{
     ...Details of implementation.....
}

新的ngOnDestroy方法应如下所示

ngOnDestroy(): void {
  this.row.close = false;
}
相关问题