代码之家  ›  专栏  ›  技术社区  ›  Felix Lemke

布线前的角度动画

  •  1
  • Felix Lemke  · 技术社区  · 8 年前

    在我目前的项目中,我试图摆脱角度动画时跳过路由。在我的模板中,我有不同的“小部件” mat卡 在一个css网格布局,我想使出现和消失顺利。

    我在子组件(路由指向的组件)中的动画如下所示

    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>
    

    卡片显示时带有动画,但布线直接更改为下一个布线,而不等待动画。我也用 animateChild() query 在过渡期内,但这没有帮助。我怎样才能让路由器等他们呢?

    谢谢,干杯!

    1 回复  |  直到 8 年前
        1
  •  3
  •   Felix Lemke    8 年前

    当路由更改时,组件将被销毁,并且不能再设置动画。如果要在组件被破坏之前对其设置动画,可以使用 CanDeactivate 守卫,确保组件在销毁之前可以被停用。

    下面是一个实现示例:

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

    然后在路由模块声明中:

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

    在那之后你可以利用 ngOnInit canDeactivate 播放开始和结束动画:

    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.

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