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

相关内容

热门资讯

透视数据!wpk插件,poke... 透视数据!wpk插件,pokerworld软件,方针教程(有挂分析)-哔哩哔哩1、打开软件启动之后找...
透视有挂!wpk私人局辅助是真... 透视有挂!wpk私人局辅助是真的吗,wejoker开挂,演示教程(有挂详细)-哔哩哔哩暗藏猫腻,小编...
透视总结!wepoker黑侠破... 透视总结!wepoker黑侠破解,德州私人局怎么透视,诀窍教程(有挂秘笈)-哔哩哔哩1、超多福利:超...
透视苹果版!德普之星怎么设置埋... 透视苹果版!德普之星怎么设置埋牌,哈糖大菠萝破解器,妙招教程(有挂教学)-哔哩哔哩在进入德普之星怎么...
透视好友!wepoker究竟有... 透视好友!wepoker究竟有没有透视,wejoker辅助软件,绝活儿教程(有挂功能)-哔哩哔哩1、...
透视好牌!xpoker透视辅助... 透视好牌!xpoker透视辅助,wepoker脚本下载,举措教程(有挂猫腻)-哔哩哔哩1、许多玩家不...
透视辅助!wepoker有人用... 透视辅助!wepoker有人用过吗,hhpoker是正规的吗,总结教程(有挂工具)-哔哩哔哩1、下载...
透视智能ai!德州透视是真的假... 透视智能ai!德州透视是真的假的,wepoker开脚本视频,法子教程(今日头条)-哔哩哔哩德州透视是...
透视脚本!佛手在线大菠萝智能辅... 透视脚本!佛手在线大菠萝智能辅助器,德州局透视脚本下载安装最新版本,大纲教程(有挂技巧)-哔哩哔哩1...
透视了解!哈糖大菠萝免费辅助器... 透视了解!哈糖大菠萝免费辅助器,werplan外卦神器,手筋教程(有挂实锤)-哔哩哔哩1、哈糖大菠萝...