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

相关内容

热门资讯

透视挂!aapoker能控制牌... 透视挂!aapoker能控制牌吗,赣牌圈破解器,果然有挂(解迷黑科技教程)-哔哩哔哩1、打开软件启动...
透视ai!哈糖大菠萝辅助器,w... 透视ai!哈糖大菠萝辅助器,wepoker私人局有透视吗,方针教程(好像是真的挂)-哔哩哔哩1、we...
透视苹果版本!wpk辅助最怕三... 透视苹果版本!wpk辅助最怕三个东西(透视)开挂辅助技巧(其实是真的挂)-哔哩哔哩1、wpk辅助最怕...
透视苹果版!werplan透视... 透视苹果版!werplan透视挂,玉海楼茶苑脚本,总是真的有挂(详情分享教程)-哔哩哔哩1、起透看视...
透视教学!pokemmo修改器... 透视教学!pokemmo修改器手机版,佛手在线大菠萝技巧,练习教程(切实是有挂)-哔哩哔哩佛手在线大...
透视新版!破解辅助插件wepo... 透视新版!破解辅助插件wepoker(透视)开挂辅助工具(好像真的有挂)-哔哩哔哩1、破解辅助插件w...
透视辅助!wepoker底牌透... 透视辅助!wepoker底牌透视,广西微乐小程序辅助器,好像有挂(专业技巧教程)-哔哩哔哩1、这是跨...
透视模拟器!wepokerpl... 透视模拟器!wepokerplus辅助,wepoker私人局透视教程,诀窍教程(确实存在有挂)-哔哩...
透视稳赢!wepoker辅助插... 透视稳赢!wepoker辅助插件功能(透视)开挂辅助插件(果然存在有挂)-哔哩哔哩1)wepoker...
备受关注的!werplan免费... 备受关注的!werplan免费挂下载,心悦填大坑规律,总是有挂(解密微扑克教程)-哔哩哔哩1、实时心...