在Angular 11中,如果使用*ngIf结合:enter和:leave动画,可能会遇到动画不正常工作的问题。解决方法是使用AnimationBuilder来创建动画,并在动画完成后手动删除元素。
具体实现可以参考以下代码示例:
// 在组件中引入AnimationBuilder import { AnimationBuilder } from '@angular/animations';
@Component({ ... }) export class MyComponent { constructor(private animationBuilder: AnimationBuilder) {}
// 在ngAfterViewInit生命周期函数中,使用AnimationBuilder创建动画 ngAfterViewInit() { if (this.shouldShow) { // 定义动画 const animation = this.animationBuilder.build([ style({ opacity: 0 }), animate('200ms ease-in-out', style({ opacity: 1 })), ]); // 获取元素 const element = document.getElementById('my-element'); // 执行动画 const player = animation.create(element); player.play(); } }
// 在ngOnDestroy生命周期函数中,手动删除元素 ngOnDestroy() { const element = document.getElementById('my-element'); if (element) { element.parentNode.removeChild(element); } } }
注意,在动画完成后手动删除元素是至关重要的,否则动画可能会出现一些不可预测的行为。