是否可以为 mat-tree 设置动画? (Angular Material)

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

我正在使用 Angular Materials 的 mat-tree (https://material.angular.io/components/tree/overview)。展开父树节点时,我想为子树节点的出现和消失设置动画。 这是我希望动画的示例:

我知道 Angular 提供了动画功能,但我无法找到如何为 mat-tree 设置动画。

是否可以为 Angular Material 的 mat-tree 设置动画?或者,如果我想要那种动画,我是否必须编写自己的树形菜单代码?

只是给标签mat-tree-node添加了动画 你的动画可以像

 animations: [

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

但是如果你不想让主树动起来,你必须使用一些像

 animations: [

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

然后你使用[@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>

stackblitz

按照接受的答案中的方法使用子节点垂直滑动 in/out 的动画来执行此操作,您可以使用嵌套树。 Stackblitz

给组件添加动画:

  @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)')])
      ])
    ]
  })

将动画应用于包含子节点的元素:

<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>

隐藏元素上的溢出:

.example-tree ul {
  overflow: hidden;
}