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

相关内容

热门资讯

透视app!wepoker轻量... 透视app!wepoker轻量版透视系统(透视)四川微乐微信麻将小程序辅助(好像存在有辅助辅助器)-...
透视好牌!wpk透视是真的吗(... 透视好牌!wpk透视是真的吗(透视)福建大玩家辅助器(其实是有辅助app)-哔哩哔哩在进入福建大玩家...
透视透视!wpk软件是真的吗(... 透视透视!wpk软件是真的吗(透视)微乐四川麻将辅助器(本来是有辅助安装)-哔哩哔哩1、微乐四川麻将...
透视攻略!wpk辅助购买(透视... 透视攻略!wpk辅助购买(透视)新玄龙开挂图片(其实是真的辅助修改器)-哔哩哔哩1、完成新玄龙开挂图...
透视软件!大菠萝手游辅助(透视... 透视软件!大菠萝手游辅助(透视)微信小程序微乐辅助器(竟然存在有辅助平台)-哔哩哔哩1、进入游戏-大...
据玩家消息!wpk透视插件(透... 据玩家消息!wpk透视插件(透视)广西老友玩有破解(总是存在有辅助插件)-哔哩哔哩1、完成广西老友玩...
透视攻略!wepoker透视脚... 透视攻略!wepoker透视脚本网页(透视)麻将外卦软件框架模式(果然有辅助平台)-哔哩哔哩1、首先...
截至目前!拱趴大菠萝怎么开挂(... 截至目前!拱趴大菠萝怎么开挂(透视)桂麻圈破解版ios(真是有辅助神器)-哔哩哔哩1、实时桂麻圈破解...
据了解!hhpoker到底可以... 据了解!hhpoker到底可以作必弊码(透视)新518互游插件(本来真的有辅助安装)-哔哩哔哩1、新...
透视有挂!德普之星私人局辅助免... 透视有挂!德普之星私人局辅助免费(透视)佛手在线辅助器苹果版(本来是真的辅助app)-哔哩哔哩1、许...