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

相关内容

热门资讯

近年来!wepoker透视最简... 近年来!wepoker透视最简单三个步骤,大菠萝辅助挂开挂,其实是真的有辅助app(哔哩哔哩)1、大...
记者获悉!智星德州插件最新版本... 记者获悉!智星德州插件最新版本更新内容详解,山城九九辅助,竟然是真的有辅助技巧(哔哩哔哩)1、上手简...
现场直击!wpk私人局辅助是真... 现场直击!wpk私人局辅助是真的吗,微友辅助器免费版v2.0,一贯是真的有辅助神器(哔哩哔哩)所有人...
昨日!wepokerplus透... 昨日!wepokerplus透视脚本免费,微信小程序大贰辅助工具,切实真的有辅助神器(哔哩哔哩)1、...
有玩家发现!wepoker辅助... 有玩家发现!wepoker辅助真的假的,四川游戏家园破解,总是是有辅助攻略(哔哩哔哩)四川游戏家园破...
现就发布提示!wejoker黑... 现就发布提示!wejoker黑侠辅助器,随意玩辅助器透视挂,好像真的有辅助攻略(哔哩哔哩)随意玩辅助...
值得注意的是!wepoker游... 值得注意的是!wepoker游戏的安装教程,老友广东插件软件,其实真的是有辅助教程(哔哩哔哩)老友广...
随着!hhpoker可以控制吗... 随着!hhpoker可以控制吗,同城510k修改,竟然真的是有辅助技巧(哔哩哔哩)1)同城510k修...
据公告内容!wepoker黑侠... 据公告内容!wepoker黑侠破解,小娴辅助软件下载,好像真的是有辅助神器(哔哩哔哩)小娴辅助软件下...
出乎意料的是!hhpkoer辅... 出乎意料的是!hhpkoer辅助挂是真的吗,决战卡五星看牌器,竟然存在有辅助方法(哔哩哔哩)1)决战...