在我当前的项目中,我试图摆脱路由时跳过的 Angular 动画。在我的模板中,我有不同的“小部件”mat-card在 css-grid 布局中,我想让它平滑地出现和消失。
我的子组件中的动画(路线指向的)看起来像
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
在过渡中,但这没有帮助。如何让路由器等待它们?
谢谢并欢呼!
当路线发生变化时,组件将被销毁并且无法再进行动画处理。如果你想在组件被破坏之前为它设置动画,你可以使用CanDeactivate
防护,确保组件在销毁之前可以被停用。
这是一个实现示例:
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
然后在路由模块声明中:
RouterModule.forChild([
{ path: '', component: HelloComponent,
canDeactivate: [CanDeactivateGuard] }
])
之后您可以使用ngOnInit
and 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();
}
这是使用此建议解决方案的运行示例。 https://stackblitz.com/edit/stackoverflow-51763987
为了使其易于使用,我制作了一个处理动画的抽象组件,只需扩展抽象组件即可将动画行为添加到任何组件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)