首页 > 解决方案 > 动画兄弟元素

问题描述

在我的应用程序中,我有 2 个兄弟元素。一个元素被隐藏,我可以通过按钮切换它的可见性。当这个隐藏的元素变得可见时,我添加了一个动画。问题是,兄弟元素没有动画。它只是跳到它的新位置。知道如何解决这个问题吗?请参阅stackblitz示例。

app.component.ts

import { Component } from '@angular/core';
import { animate, style, transition, trigger } from "@angular/animations";

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css',],
  animations: [
      trigger(
          "enterAnimation", [
              transition(":enter", [
                  style({transform: "translateY(-100%)", opacity: 0}),
                  animate("500ms", style({transform: "translateY(0)", opacity: 1}))
              ]),
              transition(":leave", [
                  style({transform: "translateY(0)", opacity: 1}),
                  animate("500ms", style({transform: "translateY(-100%)", opacity: 0}))
              ])
          ]
      )
  ],
})
export class AppComponent  {
  visible: boolean = false;

  toggle(): void {
    this.visible = !this.visible;
  }
}

app.component.html

<div class="box1" *ngIf="visible" [@enterAnimation]></div>
<div class="box2"></div>

<button (click)="toggle()">Toggle</button>

标签: angularangular-animations

解决方案


而不是使用变换使用高度来获得这种效果。演示

trigger(
          "enterAnimation", [
              transition(":enter", [
                  style({height: "0px", opacity: 0}),
                  animate("500ms", style({height: "50px", opacity: 1}))
              ]),
              transition(":leave", [
                  style({height: "50px", opacity: 1}),
                  animate("500ms", style({height: "0px", opacity: 0}))
              ])
          ]
      )

推荐阅读