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、完成...
必备透视!线上德州的辅助器是什... 必备透视!线上德州的辅助器是什么,epoker透视底牌(透视)原来一直总是有辅助攻略(哔哩哔哩)1、...
分享透视!红龙poker辅助,... 分享透视!红龙poker辅助,拱趴大菠萝挂(透视)一直是真的有辅助软件(哔哩哔哩)1、金币登录送、破...
必备透视!pokemmo内置修... 必备透视!pokemmo内置修改器,约局吧能不能开挂(透视)原来存在有辅助app(哔哩哔哩)1、首先...
关于透视!wepoker安装教... 关于透视!wepoker安装教程,哈糖大菠萝能开挂吗(透视)果然一直都是有辅助工具(哔哩哔哩)1、上...
解谜透视!poker mast... 解谜透视!poker master辅助,德州圈脚本(透视)竟然存在有辅助插件(哔哩哔哩)1、每一步都...
有挂透视!sohoo poke... 有挂透视!sohoo poker辅助器,德州透视是真的吗(透视)原来是真的有辅助插件(哔哩哔哩)1、...
推荐透视!佛手在线是不是有挂,... 推荐透视!佛手在线是不是有挂,poker world辅助器(透视)一直真的有辅助app(哔哩哔哩)1...
了解透视!拱趴大菠萝机器人,红... 了解透视!拱趴大菠萝机器人,红龙poker辅助(透视)果然真的有辅助攻略(哔哩哔哩)1.拱趴大菠萝机...
科普透视!pokemmo脚本辅... 科普透视!pokemmo脚本辅助器下载,sohoopoker辅助(透视)原来存在有辅助脚本(哔哩哔哩...