Search code examples
angulartreeangular-materialangular-animations

Is it possible to animate mat-tree? (Angular Material)


I am using mat-tree (https://material.angular.io/components/tree/overview) from Angular Materials. When expanding a parent-tree-node, I want to animate the appearance and disappearance of the child-tree-nodes. Here is an example of how I would like the animation to be:

tree animation

I know that Angular is offering a feature for animations, but yet I couldn't find out how to animate mat-tree.

Is it possible to animate mat-tree of Angular Material? Or am I forced to code my own tree-menu if I want that kind of animation?


Solution

  • it's just add animation to the tag mat-tree-node your animation can be like

     animations: [
    
        trigger('simpleFade', [
          transition(':enter', [
            style({ opacity:0 }),
            animate(350)
          ])])]
    

    But if you don't want animate the main tree, you must use some like

     animations: [
    
        trigger('simpleFade', [
          transition('*=>1', [
            style({ opacity:0 }),
            animate(350)
          ])])]
    

    then you use [@simpleFade]="node.level?1:0"

    <mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
    <!--see that you only want the animation when becomes 1, so check the level-->
      <mat-tree-node *matTreeNodeDef="let node" matTreeNodePadding 
                          [@simpleFade]="node.level?1:0">
        <button mat-icon-button disabled></button>
        {{node.name}}
      </mat-tree-node>
    <!--see that you only want the animation when becomes 1, so check the level-->
      <mat-tree-node *matTreeNodeDef="let node;when: hasChild" matTreeNodePadding 
                           [@simpleFade]="node.level?1:0">
        <button mat-icon-button matTreeNodeToggle
                [attr.aria-label]="'toggle ' + node.name">
          <mat-icon class="mat-icon-rtl-mirror">
            {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
          </mat-icon>
        </button>
        {{node.name}}
      </mat-tree-node>
    </mat-tree>
    

    See stackblitz