Angular Material - MatTable expandable row animation

Viewed 3347

Currently I have built a MatTable with expandable rows:

<!-- Hidden cell -->
<ng-container matColumnDef="expandedDetail">
    <td mat-cell *matCellDef="let myModel" [attr.colspan]="displayedColumns.length">
        <div
            class="detail-cell"
            [@detailExpand]="myModel.isExpanded ? 'expanded' : 'collapsed'"
        >
            <my-inner-component
                ...
            ></my-inner-component>
        </div>
    </td>
</ng-container>

And the row:

<!-- Hidden row -->
<tr
    mat-row
    *matRowDef="let myModel; columns: ['expandedDetail']"
></tr>

The expandable row has an animation attached:

animations: [
    trigger('detailExpand', [
        state('collapsed, void', style({ height: '0px', minHeight: '0', display: 'none' })),
        state('expanded', style({ height: '*' })),
        transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)'))
    ])
]

Being that I display a lot of rows, and that my-inner-component is a heavy component, I want it to be created only when the row gets expanded.
So i added:

*ngIf="myModel.isExpanded"

to the containing div.

However the animation, obviously, breaks.
How can I solve this problem? I'd like to maintain the animation if possible.

1 Answers

Use entry/leave transitions:

Animations in ts file:

animations: [
  trigger(
    'detailExpand', [
      transition(':enter', [
        style({ height: '0px', minHeight: '0', display: 'none' }),
        animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)', style({ height: '*' }))
      ]),
      transition(':leave', [
        style({ height: '*' }),
        animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)', style({ height: '0px', minHeight: '0', display: 'none' }))
      ])
    ]
  )
]

Using it in template:

<my-inner-component *ngIf="myModel.isExpanded" [@detailExpand]>
  ...
</my-inner-component>
Related