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

相关内容

热门资讯

科普透视!拱趴大菠萝怎么开挂,... 科普透视!拱趴大菠萝怎么开挂,pokermaster修改器(透视)原来是有辅助教程(哔哩哔哩)一、拱...
科普透视!德州辅助工具到底怎么... 科普透视!德州辅助工具到底怎么样,epoker免费透视脚本(透视)好像真的有辅助脚本(哔哩哔哩)1、...
推荐透视!拱趴大菠萝有什么挂,... 推荐透视!拱趴大菠萝有什么挂,约局吧开挂神器是真的吗(透视)好像真的是有辅助app(哔哩哔哩)1、完...
曝光透视!云扑克有透视吗,德州... 曝光透视!云扑克有透视吗,德州局透视脚本下载安装最新版本(透视)好像真的是有辅助软件(哔哩哔哩)1、...
教你透视!sohoo辅助,po... 教你透视!sohoo辅助,pokemmo辅助器(透视)一贯真的有辅助神器(哔哩哔哩)1、pokemm...
详细透视!拱趴大菠萝挂哪里,拱... 详细透视!拱趴大菠萝挂哪里,拱趴大菠萝有挂吗(透视)本来一直总是有辅助插件(哔哩哔哩)进入游戏-大厅...
关于透视!来玩app 德州 辅... 关于透视!来玩app 德州 辅助,werplan透视挂(透视)原来一直总是有辅助方法(哔哩哔哩)1、...
揭幕透视!agpoker辅助,... 揭幕透视!agpoker辅助,pokemmo脚本辅助下载(透视)确实一直总是有辅助技巧(哔哩哔哩)p...
分享透视!哈糖大菠萝挂,pok... 分享透视!哈糖大菠萝挂,pokerworld软件(透视)本来是真的有辅助软件(哔哩哔哩)1、玩家可以...
必备透视!智星德州插件,aa ... 必备透视!智星德州插件,aa poker辅助(透视)一贯真的是有辅助攻略(哔哩哔哩)智星德州插件能透...