You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用RxJS的fromEvent监听Angular动画@animation.done事件?

解决Angular中用RxJS监听动画done事件的问题

你遇到的问题根源在于:Angular的@animation.done是框架层面的合成事件,并非原生DOM事件,而fromEvent只能监听原生DOM事件,所以直接用fromEvent绑定@animation.done不会生效。

正确实现方式

可以通过Angular的Renderer2监听动画事件,再用RxJS的fromEventPattern封装成Observable,这是最贴合RxJS风格的做法:

import { Component, ElementRef, Renderer2, OnInit, OnDestroy } from '@angular/core';
import { fromEventPattern, tap, takeUntil } from 'rxjs';
import { Subject } from 'rxjs';

@Component({
  // 组件元数据
})
export class YourComponent implements OnInit, OnDestroy {
  @HostBinding('@animation') animated = true;
  private destroy$ = new Subject<void>();

  constructor(private el: ElementRef, private renderer: Renderer2) {}

  ngOnInit(): void {
    // 封装动画完成事件为Observable
    const animationDone$ = fromEventPattern(
      // 绑定监听的回调
      (handler) => this.renderer.listen(this.el.nativeElement, '@animation.done', handler),
      // 取消监听的回调
      (_handler, unsubscribeFn) => unsubscribeFn()
    );

    // 订阅事件
    animationDone$.pipe(
      tap(() => console.log('animation end')),
      takeUntil(this.destroy$) // 组件销毁时自动取消订阅
    ).subscribe();
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

关键说明

  1. Renderer2.listen是Angular提供的用于监听元素事件的API,它支持监听框架合成的动画事件
  2. fromEventPattern可以将基于回调的API转换成Observable,完美适配Renderer2的监听逻辑
  3. 用takeUntil和destroy$ Subject确保组件销毁时取消订阅,避免内存泄漏

内容的提问来源于stack exchange,提问作者Raziel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:23:22