angularrxjsangular-directivengzone

Should we use NgZone.runOutsideAngular() when handling fromEvent with filters in Angular


I came across this implementation of the outsideCLick directive

ngOnInit() {
    this._ngZone.runOutsideAngular(() => {
      fromEvent<MouseEvent>(document, DomEventsEnum.MOUSEDOWN, { capture: true })
        .pipe(
          filter(() => this.clickOutsideEnabled),
          filter((event) => !this.isClickInside(event.target as HTMLElement)),
          takeUntilDestroyed(this._destroyRef),
        )
        .subscribe((event) => {
          event.preventDefault();
          event.stopPropagation();
          this._ngZone.run(() => this.clickOutside.emit(event));
        });
    });
  }

I'm wondering if there is any actual benefit in wrapping this logic with ngZone.runOutsideAngular()?

Since CD is only triggered when clickOutside.emit() is called due to filters in any case - is runOutsideAngular actually doing anything useful here?


Solution

  • Yes, Because in zonefull apps, fromEvent internally invokes addEventListener which will schedule CD everytime an event is emitted.

    With the implementation you gave us, it'll only schedule CD when calling the emit.