更改路线时,我已在Angular 7中设置了幻灯片动画。我现在遇到的问题是动画很不稳定,因为我导航到的Component在OnInit
生命周期的动画过程中正在执行代码。
在动画完成后如何为组件初始化代码以防止掉帧?
编辑:
我正在使用路由器动画,这是我的设置:
app.component.html
:
<div [@routeAnimations]="prepareRoute(outlet)">
<router-outlet #outlet="outlet"></router-outlet>
</div>
app.component.ts
:
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
animations: [routeAnimations]
})
export class AppComponent {
prepareRoute(outlet: RouterOutlet) {
return outlet && outlet.activatedRouteData && outlet.activatedRouteData.animation;
}
}
app-routing.module.ts
:
const routes: Routes = [
{
path: 'sign-in',
loadChildren: './modules/sign-in/sign-in.module#SignInModule',
data: {animation: 'slideLeft'}
},
{
path: 'dashboard',
component: DashboardComponent,
data: {animation: 'slideRight'}
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
animations.ts
:
export const routeAnimations =
trigger('routeAnimations', [
transition('slideLeft => slideRight', [
// ...a bunch of animation code...
]),
transition('slideRight => slideLeft', [
// ...a bunch of animation code...
])
]);
答案 0 :(得分:2)
您需要将动画中的 start 和 done 事件公开给子组件。
@Component({..})
export class AppComponent {
public start$: Subject<AnimationEvent> = new Subject();
public done$: Subject<AnimationEvent> = new Subject();
}
<div [@routeAnimations]="prepareRoute(outlet)"
(@routeAnimations.start)="start$.next($event)"
(@routeAnimations.done)="done$.next($event)">
<router-outlet #outlet="outlet"></router-outlet>
</div>
现在将AppComponent
注入到路由器中使用的子组件中。
@Component({..})
export class ChildComponent implements OnDestroy {
private readonly _destroyed: Subject<void> = new Subject();
public constructor(app: AppComponent) {
app.done$
.pipe(first(), takeUntil(this._destroyed))
.subscribe(()=> {
// do special work here
});
}
public ngOnDestroy() {
this._destroyed.next();
}
}