Programatically close an expanded row with a button

Viewed 663

I've used this model to create a table with expanded rows :

https://stackblitz.com/edit/angular-material2-expandable-rows-filter-pagination-sorting?file=app%2Fcdk-detail-row.directive.ts

Problem is that I cannot get a row to expand or close without clicking on it.

For example :

When I click on row, it expands in the ng-template :

<ng-template #tpl let-element>
    <div class="mat-row detail-row" [@detailExpand] style="overflow: hidden">
       <button type="button" (click)="closeRow()">Close Row</button>
    </div>
</ng-template>

I'd like to be able to close that row by clicking on the button inside the ng-template.

Hope this is not too confused.

1 Answers

The problem is solved and you can try it here: https://stackblitz.com/edit/angular-material2-expandable-rows-filter-pagination-sort-7jpsik?file=app%2Ftable-example.ts

What was changed:

cdk-detail-row.directive.ts

adding emmitter

31: @Output() toggleChange = new EventEmitter<CdkDetailRowDirective>(); // added

emitting on toggle

47: this.toggleChange.emit(this); // added

table-example.html

binding toggle

39: (toggleChange)="onToggleChange($event)"

adding button to close row on click

48: <button type="button" (click)="closeRow()">Close Row</button>

table-example.ts

adding variable to track what row is expanded

30: private openedRow: CdkDetailRowDirective

managing cdkDetailRow.expended

43-52:

  onToggleChange(cdkDetailRow: CdkDetailRowDirective) : void {
    if (this.openedRow && this.openedRow.expended) {
      this.openedRow.toggle();      
    }
    this.openedRow = cdkDetailRow.expended ? cdkDetailRow : undefined;
  }

  closeRow() {
    this.onToggleChange(this.openedRow);
  }
Related