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中调用无法正确工作,因为组件尚未完全初始化并渲染。

相关内容

热门资讯

透视关于!hhpoker有作弊... 透视关于!hhpoker有作弊的吗,hhpoker有没有作弊挂-竟然真的有辅助脚本(哔哩哔哩)1、首...
透视必备!德普之星有透视辅助吗... 透视必备!德普之星有透视辅助吗,德普之星透视辅助软件是真的吗-一贯一直都是有辅助技巧(哔哩哔哩);1...
透视有挂!黑侠破解wepoke... 透视有挂!黑侠破解wepoker,wepoker透视脚本免费使用视频-一直是有辅助插件(哔哩哔哩)暗...
透视揭幕!wpk安卓下载辅助,... 透视揭幕!wpk安卓下载辅助,wpk有作弊吗-其实真的有辅助脚本(哔哩哔哩)进入游戏-大厅左侧-新手...
透视教你!菠萝辅助器免费版的功... 透视教你!菠萝辅助器免费版的功能介绍,pokemmo脚本辅助下载-都是真的是有辅助工具(哔哩哔哩)1...
透视教你!wpk模拟器是什么,... 透视教你!wpk模拟器是什么,wpk控制牌是真的吗-其实一直都是有辅助神器(哔哩哔哩)1)辅助插件:...
透视有挂!wpk有那种辅助吗,... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在这款游戏中打...
透视开挂!hhpoker有没有... 透视开挂!hhpoker有没有作弊辅助,hhpoker辅助器视频-一贯真的有辅助app(哔哩哔哩)透...
透视辅助!扑克之星辅助,佛手大... 透视辅助!扑克之星辅助,佛手大菠萝13道挂哪里-其实真的是有辅助方法(哔哩哔哩)1、佛手大菠萝13道...
透视总结!wepoker怎么发... 透视总结!wepoker怎么发冤家牌,wepoker提高好牌率-切实真的是有辅助攻略(哔哩哔哩)1、...