当路由更改时,组件将被销毁,并且不能再设置动画。如果要在组件被破坏之前对其设置动画,可以使用
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.
为了使其易于使用,我制作了一个处理动画的抽象组件,通过扩展抽象组件将动画行为添加到任何组件。