【问题标题】:Angular animate before routing路由前的角度动画
【发布时间】:2019-01-16 17:45:42
【问题描述】:

在我当前的项目中,我试图摆脱路由时跳过的 Angular 动画。在我的模板中,我在 css-grid 布局中使用 mat-card 获得了不同的“小部件”,我想让它们平滑地出现和消失。

我在子组件(路由指向的)中的动画看起来像

animations: [
  trigger('cardAnimation', [
    state('void', style({ opacity: 0, transform: 'scale(0.5)' })),
    state('*', style({ opacity: 1, transform: 'scale(1)' })),
    transition('void => *', animate('500ms ease-in')),
    transition('* => void', animate('500ms ease-in'))
  ])
]

简化的模板如下所示

<mat-card @cardAnimation>
</mat-card>

<mat-card @cardAnimation>
</mat-card>

卡片出现动画,但路由直接更改为下一个路由,无需等待动画。我还在转换内部的query 中使用animateChild() 进行了测试,但这无济于事。如何让路由器等待他们?

感谢和欢呼!

【问题讨论】:

    标签: angular animation angular-routing angular-animations


    【解决方案1】:

    当路由改变时,组件被销毁并且不能再被动画化。如果您想在组件被销毁之前对其进行动画处理,您可以使用CanDeactivate 保护,以确保组件可以在销毁之前被停用。

    这是一个实现示例:

    export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
      canDeactivate(component: CanComponentDeactivate) {
        return component.canDeactivate ? component.canDeactivate() : true;
      }
    }
    

    然后在路由模块声明中:

    RouterModule.forChild([
          { path: '', component: HelloComponent,
      canDeactivate: [CanDeactivateGuard] }
    ])
    

    之后你可以使用ngOnInitcanDeactivate来播放开始和结束动画:

    ngOnInit() {
      this.animation = this._builder.build(this.slideIn(this.ANIMATION_TIME));
      this.player = this.animation.create(this.el.nativeElement, {});
      this.player.play();
    }
    
    canDeactivate() {
      this.animation = this._builder.build(this.slideOut(this.ANIMATION_TIME));
      this.player = this.animation.create(this.el.nativeElement, {});
      this.player.play();
      return timer(this.ANIMATION_TIME).pipe(mapTo(true)).toPromise();
    }
    

    Here is a running example with this suggested solution.

    为了简单易用,我制作了一个处理动画的抽象组件,通过简单地扩展抽象组件来将动画行为添加到任何组件。

    【讨论】:

    • @Jago 已修复,该示例很旧并且遵循旧的 Angular 项目树。
    猜你喜欢
    • 2021-05-17
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2017-09-07
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多