gpt4 book ai didi

angular - 如何在 Angular 动画之后运行代码?

转载 作者:行者123 更新时间:2023-12-02 03:23:30 27 4
gpt4 key购买 nike

我在 Angular 7 中设置了更改路线时的幻灯片动画。我现在遇到的问题是动画卡顿,因为我导航到的组件正在 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...
])
]);

最佳答案

您需要将动画中的 startdone 事件公开给子组件。

@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 注入(inject)到路由器中使用的子组件中。

@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();
}
}

关于angular - 如何在 Angular 动画之后运行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54099265/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com