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辅助器怎么用,破解辅助插件wepoker,法子教程(一直是真的挂)-哔哩哔...
透视苹果版!wepoker辅助... 透视苹果版!wepoker辅助器软件下载(透视)开挂辅助挂(果然真的有挂)-哔哩哔哩1、超多福利:超...
透视能赢!aapoker辅助怎... 透视能赢!aapoker辅助怎么用,hhpoker一直输有挂吗,模板教程(都是真的有挂)-哔哩哔哩h...
透视苹果版本!wepoker私... 透视苹果版本!wepoker私人定制透视(透视)开挂辅助脚本(一贯是真的挂)-哔哩哔哩1、很好的工具...
透视数据!wpk透视怎么安装,... 透视数据!wpk透视怎么安装,哈糖大菠萝软件下载,诀窍教程(本来是真的挂)-哔哩哔哩一、哈糖大菠萝软...
透视ai代打!德州来玩辅助器(... 透视ai代打!德州来玩辅助器(透视)开挂辅助器(其实有挂)-哔哩哔哩德州来玩辅助器辅助器中分为三种模...
透视辅助!wepoker轻量版... 透视辅助!wepoker轻量版书签,智星德州可以透视吗,学习教程(其实有挂)-哔哩哔哩1、起透看视 ...
透视新版!wepoker轻量版... 透视新版!wepoker轻量版透视方法(透视)开挂辅助挂(一直真的有挂)-哔哩哔哩1、wepoker...
透视脚本!wepoker透视版... 透视脚本!wepoker透视版下载,hh poker透视器下载,烘培教程(一直真的是有挂)-哔哩哔哩...
透视代打ai!pokemmo脚... 透视代打ai!pokemmo脚本辅助(透视)开挂辅助神器(一直是真的挂)-哔哩哔哩1)pokemmo...