Angular动画:组件在触发动画之前被销毁。
创始人
2024-10-24 14:00:54
0

一个可能的解决方法是将动画触发放在ngAfterViewInit生命周期钩子中执行,而不是ngOnInit中。这样可以确保组件已经初始化并完全渲染,不会在动画触发之前被销毁。 示例代码:

import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'], animations: [ trigger('myAnimation', [ state('start', style({ opacity: 1 })), state('end', style({ opacity: 0 })), transition('start => end', [ animate('1s') ]) ]) ] }) export class MyComponent implements AfterViewInit { @ViewChild('myElement') myElement: ElementRef;

ngOnInit() { // This won't work because the element hasn't been rendered yet this.myElement.nativeElement.classList.toggle('myClass'); this.triggerAnimation(); }

ngAfterViewInit() { // This will work because the element has been rendered this.myElement.nativeElement.classList.toggle('myClass'); this.triggerAnimation(); }

triggerAnimation() { this.state = 'end'; } }

在这个示例中,我们在ngAfterViewInit的生命周期钩子中调用triggerAnimation()方法来触发动画。在ngOnInit中调用无法正确工作,因为组件尚未完全初始化并渲染。

相关内容

热门资讯

透视挂!竞技联盟破解版最新版(... 透视挂!竞技联盟破解版最新版(透视)开挂辅助挂(确实是真的挂)-哔哩哔哩1、实时竞技联盟破解版最新版...
透视ai代打!wepoker插... 透视ai代打!wepoker插件辅助,购买的wpk辅助在哪里下载,诀窍教程(原来真的有挂)-哔哩哔哩...
透视线上!hhpoker软件安... 透视线上!hhpoker软件安装包(透视)开挂辅助器(本来存在有挂)-哔哩哔哩1、完成hhpoker...
透视新版!wepoker怎么破... 透视新版!wepoker怎么破解游戏,uupoker有透视吗,大纲教程(切实是有挂)-哔哩哔哩1、全...
透视app!来玩德州破解器,w... 透视app!来玩德州破解器,wepoker辅助器软件下载,方针教程(真是有挂)-哔哩哔哩1)wepo...
透视辅助!wejoker辅助脚... 透视辅助!wejoker辅助脚本(透视)开挂辅助工具(果然真的是有挂)-哔哩哔哩1、wejoker辅...
透视app!hhpoker辅助... 透视app!hhpoker辅助实战视频,wepoker透视功能下载,法子教程(切实有挂)-哔哩哔哩一...
透视输赢!约局吧是否有挂(透视... 透视输赢!约局吧是否有挂(透视)开挂辅助软件(其实是有挂)-哔哩哔哩约局吧是否有挂辅助器中分为三种模...
透视代打!来玩德州破解器,we... 透视代打!来玩德州破解器,we-poker辅助器,手册教程(总是真的有挂)-哔哩哔哩1、来玩德州破解...
透视辅助挂!拱趴大菠萝万能辅助... 透视辅助挂!拱趴大菠萝万能辅助器(透视)开挂辅助脚本(一贯是真的挂)-哔哩哔哩1、拱趴大菠萝万能辅助...