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:
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?
MatTree 's treeControl provide a expandAll method which you can use to expand all tree nodes, and collapseAll to close all tree nodes. You can can instance of MatTree via ViewChild and call expandAll in ngAfterViewInit life hook to make it expand by default. see example. Perfect.
Angular lets you define a style and transition to be applied when an element's state changes. Angular provides 3 different states which we could use in our animation code: Wildcard ( * ) - this is the default or all states of the element, for example active => * represents a state change from active to anything else.
The <mat-tree> directive is used to create trees in Angular. The tree is a type of structure that contains data organized in a hierarchical way. Each data item is represented by a node of the tree. The Angular Material Tree is an enhancement over the previous structure, Component Dev Kit Tree (cdk-tree).
Angular's animation system is built on CSS functionality, which means you can animate any property that the browser considers animatable. This includes positions, sizes, transforms, colors, borders, and more. The W3C maintains a list of animatable properties on its CSS Transitions page.
Following the method in the accepted answer to do this with an animation of the child nodes sliding in/out vertically you can use a nested tree. Stackblitz
Add the animation to the component:
@Component({
selector: 'tree-nested-overview-example',
templateUrl: 'tree-nested-overview-example.html',
styleUrls: ['tree-nested-overview-example.css'],
animations:[
trigger('slideVertical', [
state(
'*',
style({
height: 0
})
),
state(
'show',
style({
height: '*'
})
),
transition('* => *', [animate('400ms cubic-bezier(0.25, 0.8, 0.25, 1)')])
])
]
})
Apply the animation to the element containing the child nodes:
<mat-nested-tree-node *matTreeNodeDef="let node; when: hasChild">
<li>
<div class="mat-tree-node">
<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}}
</div>
<ul [@slideVertical]="treeControl.isExpanded(node) ? 'show' : null">
<ng-container matTreeNodeOutlet></ng-container>
</ul>
</li>
</mat-nested-tree-node>
Hide the overflow on the element:
.example-tree ul {
overflow: hidden;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With