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、下载好哈糖大菠萝挂脚本下载之后...
外挂攻略!红龙poker辅助工... 外挂攻略!红龙poker辅助工具,来玩app破解-果然是真的有辅助工具(哔哩哔哩)1、进入游戏-大厅...
外挂方式!哈糖大菠萝能开挂吗,... 外挂方式!哈糖大菠萝能开挂吗,pokernow辅助控制-原来是真的有辅助方法(哔哩哔哩)1、哈糖大菠...
外挂模块!xpoker辅助助手... 外挂模块!xpoker辅助助手,智星德州有脚本吗-总是真的有辅助app(哔哩哔哩)1、智星德州有脚本...
外挂指南书!拱趴大菠萝辅助神器... 外挂指南书!拱趴大菠萝辅助神器,大菠萝手游辅助-好像有辅助app(哔哩哔哩)1、许多玩家不知道拱趴大...
外挂指南书!竞技联盟透视插件,... 外挂指南书!竞技联盟透视插件,拱趴大菠萝万能挂图解-果然有辅助攻略(哔哩哔哩)1、让任何用户在无需拱...
外挂指南!德普之星有辅助软件吗... 外挂指南!德普之星有辅助软件吗,xpoker辅助-原来一直总是有辅助app(哔哩哔哩)1、下载好xp...
外挂举措!werplan透视挂... 外挂举措!werplan透视挂,佛手大菠萝有挂吗-果然是真的有辅助软件(哔哩哔哩)1、佛手大菠萝有挂...
外挂妙计!德扑圈透视挂,拱趴大... 您好,拱趴大菠萝机器人这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩...
外挂技法!红龙poker作必弊... 外挂技法!红龙poker作必弊指令,sohoo开挂辅助-确实是真的有辅助教程(哔哩哔哩)1、玩家可以...