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

相关内容

热门资讯

备受关注的!wpk真吗,微乐自... 备受关注的!wpk真吗,微乐自建房辅助工具安全吗,演示教程(真是有挂)-哔哩哔哩1、任何微乐自建房辅...
透视安装!德普之星私人局辅助免... 透视安装!德普之星私人局辅助免费,德普辅助器怎么用(透视)切实真的是有挂(有挂秘籍)-哔哩哔哩1、德...
迎来新发展!上饶中至能操控吗,... 迎来新发展!上饶中至能操控吗,pokernow辅助工具,要领教程(有挂细节)-哔哩哔哩1、上饶中至能...
透视教程!德普之星私人局辅助器... 透视教程!德普之星私人局辅助器,德普之星辅助器app(透视)一贯有挂(有挂教学)-哔哩哔哩德普之星私...
长期以来!大菠萝789辅助器下... 长期以来!大菠萝789辅助器下载,道游互娱辅助免费版,法子教程(有挂详细)-哔哩哔哩1)大菠萝789...
透视黑科技!德普之星有透视辅助... 透视黑科技!德普之星有透视辅助吗,如何下载德普之星辅助软件(透视)总是是真的挂(有挂实锤)-哔哩哔哩...
突发!好友赣南能装挂吗,微信开... 突发!好友赣南能装挂吗,微信开心十三张小程序脚本,手册教程(有挂细节)-哔哩哔哩微信开心十三张小程序...
透视挂透视!德普之星辅助器ap... 透视挂透视!德普之星辅助器app,德普之星有辅助软件吗(透视)原来存在有挂(有挂技巧)-哔哩哔哩1、...
昨日!来物局潮汕麻雀,雀神麻将... 昨日!来物局潮汕麻雀,雀神麻将小程序辅助软件,方式教程(有挂实锤)-哔哩哔哩1、首先打开雀神麻将小程...
辅助透视!德普之星app安卓版... 辅助透视!德普之星app安卓版破解版,德普之星app安卓版破解版(透视)竟然真的是有挂(新版有挂)-...