×

iFour Logo

Adding Event Listeners outside of the NgZone

Kapil Panchal - April 07, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Adding Event Listeners outside of the NgZone

If we're familiar with the Angular framework, we'll know that by default, any asynchronous event triggers the change detection process. In certain situations, we don't even have to worry about it; it just works as expected. However, in some cases, running the change detection process too frequently can lead to poor runtime efficiency.

Execution of code in the NgZone


Assume that we want to call the console.log method when we click the button:

Click handler in NgZone


import { AfterViewChecked, Component } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewChecked {
onClick() {
console.log("onClick");
}
ngAfterViewChecked() {
console.log("CD performed");
}
}

When we click the button, both the bound event listener and the change detection process are triggered. In a real-world scenario, instead of calling console.log, we could perform an action that does not require bindings to be updated.

Incorrect usage of the runOutsideAngular method


Although the method in question allows us to opt-out of the change detection process, it must provide code to register an event listener. As a result, the following solution, which simply runs the callback outside of the NgZone, will not prevent the change detection process from being performed:\

 
import { AfterViewChecked, Component, NgZone } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewChecked {
constructor(private readonly zone: NgZone) {}
onClick() {
this.zone.runOutsideAngular(() => {
console.log("onClick");
});
}
ngAfterViewChecked() {
console.log("CD performed");
}
}

Execution of code outside of the NgZone - using ViewChild


We may use the ViewChild decorator to get a reference to the DOM node and add an event listener in one of the following ways:

 

Click handler outside NgZone

import { AfterViewChecked, AfterViewInit, Component, ElementRef, NgZone, Renderer2, ViewChild } from "@angular/core"; import { fromEvent } from "rxjs"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent implements AfterViewInit, AfterViewChecked { @ViewChild("btn") btnEl: ElementRef; constructor( private readonly zone: NgZone, private readonly renderer: Renderer2 ) {} onClick() { console.log("onClick"); } ngAfterViewInit() { this.setupClickListener(); } ngAfterViewChecked() { console.log("CD performed"); } private setupClickListener() { this.zone.runOutsideAngular(() => { this.setupClickListenerViaNativeAPI(); // this.setupClickListenerViaRenderer(); // this.setupClickListenerViaRxJS(); }); } private setupClickListenerViaNativeAPI() { this.btnEl.nativeElement.addEventListener("click", () => { console.log("onClick"); }); } private setupClickListenerViaRenderer() { this.renderer.listen(this.btnEl.nativeElement, "click", () => { console.log("onClick"); }); }

Execution of code outside of the NgZone - using directive


While the previous paragraph's solution works well, it is a little verbose. we can encapsulate the logic in an attribute directive, which allows dependency injection to provide easy access to the underlying DOM element (ElementRef token). Then, outside of the NgZone, we can add an event listener and emit an event when it's appropriate:

 

Click handler outside NgZone

import { Directive, ElementRef, EventEmitter, NgZone, OnDestroy, OnInit, Output, Renderer2 } from "@angular/core"; @Directive({ selector: "[click.zoneless]" }) export class ClickZonelessDirective implements OnInit, OnDestroy { @Output("click.zoneless") clickZoneless = new EventEmitter(); private teardownLogicFn: Function; constructor( private readonly zone: NgZone, private readonly el: ElementRef, private readonly renderer: Renderer2 ) {} ngOnInit() { this.zone.runOutsideAngular(() => { this.setupClickListener(); }); } ngOnDestroy() { this.teardownLogicFn(); } private setupClickListener() { this.teardownLogicFn = this.renderer.listen( this.el.nativeElement, "click", (event: MouseEvent) => { this.clickZoneless.emit(event); } ); } }

Execution of code outside of the NgZone - using Event Manager Plugin


The directive-based approach has the disadvantage of not being able to be configured for an event type. Thankfully, Angular allows us to build our Event Manager Plugin. In other words, we take control of adding a listener for an event whose name corresponds to the predicate function (the supports method). If a match is found, the addEventListener method is called, allowing us to handle the job. The two methods are part of the user-defined service that is registered as an EVENT MANAGER PLUGINS token provider:

 

Click handler outside NgZone


import { Injectable } from "@angular/core";
import { EventManager } from "@angular/platform-browser";
@Injectable()
export class ZonelessEventPluginService {
manager: EventManager;
supports(eventName: string): boolean {
return eventName.endsWith(".zoneless");
}
addEventListener(
element: HTMLElement,
eventName: string,
originalHandler: EventListener
): Function {
const [nativeEventName] = eventName.split(".");
this.manager.getZone().runOutsideAngular(() => {
element.addEventListener(nativeEventName, originalHandler);
});
return () => element.removeEventListener(nativeEventName, originalHandler);
}
}
import { NgModule } from "@angular/core";
import {
BrowserModule,
EVENT_MANAGER_PLUGINS
} from "@angular/platform-browser";
import { AppComponent } from "./app.component";
import { ClickZonelessDirective } from "./click-zoneless.directive";
import { ZonelessEventPluginService } from "./zoneless-event-plugin.service";
@NgModule({
imports: [BrowserModule],
declarations: [
AppComponent,
// ClickZonelessDirective
],
bootstrap: [AppComponent],
providers: [
{
provide: EVENT_MANAGER_PLUGINS,
useClass: ZonelessEventPluginService,
multi: true
}
]
})
export class AppModule {}

Fortunately, by calling the initialization code from outside the NgZone, we can avoid triggering the change detection process:

 

3rd party lib initialized outside NgZone

import { Directive, ElementRef, NgZone, OnInit } from "@angular/core"; import tippy from "tippy.js"; @Directive({ selector: "[appTooltip]" }) export class TooltipDirective implements OnInit { constructor(private readonly zone: NgZone, private readonly el: ElementRef) {} ngOnInit() { this.zone.runOutsideAngular(() => { this.setupTooltip(); }); } private setupTooltip() { tippy(this.el.nativeElement, { content: "Bazinga!" }); } }

Conclusion


If we find ourselves in a situation where we are performing a task that does not need binding updates in response to a DOM event, we can improve the performance of our application by not triggering an unwanted change detection run Outside of the NgZone, we must be careful when registering an event listener. The most elegant and reusable solution is to use a custom Event Planner Plugin. If we're using a third-party solution that modifies the DOM, we should think about running its initialization code outside of the NgZone.

Adding Event Listeners outside of the NgZone If we're familiar with the Angular framework, we'll know that by default, any asynchronous event triggers the change detection process. In certain situations, we don't even have to worry about it; it just works as expected. However, in some cases, running the change detection process too frequently can lead to poor runtime efficiency. Table of Content 1. Execution of code in the NgZone 2. Incorrect usage of the runOutsideAngular method 3. Execution of code outside of the NgZone - using ViewChild 4. Execution of code outside of the NgZone - using directive 5. Execution of code outside of the NgZone - using Event Manager Plugin 6. Be Afraid of third-party Code 7. Conclusion Execution of code in the NgZone Assume that we want to call the console.log method when we click the button: Click handler in NgZone Click me! import { AfterViewChecked, Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent implements AfterViewChecked { onClick() { console.log("onClick"); } ngAfterViewChecked() { console.log("CD performed"); } } When we click the button, both the bound event listener and the change detection process are triggered. In a real-world scenario, instead of calling console.log, we could perform an action that does not require bindings to be updated. Incorrect usage of the runOutsideAngular method Although the method in question allows us to opt-out of the change detection process, it must provide code to register an event listener. As a result, the following solution, which simply runs the callback outside of the NgZone, will not prevent the change detection process from being performed:\   import { AfterViewChecked, Component, NgZone } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent implements AfterViewChecked { constructor(private readonly zone: NgZone) {} onClick() { this.zone.runOutsideAngular(() => { console.log("onClick"); }); } ngAfterViewChecked() { console.log("CD performed"); } } Execution of code outside of the NgZone - using ViewChild We may use the ViewChild decorator to get a reference to the DOM node and add an event listener in one of the following ways: Read More: Introduction To Angular Cli Builders   Click handler outside NgZone Click me!import { AfterViewChecked, AfterViewInit, Component, ElementRef, NgZone, Renderer2, ViewChild } from "@angular/core"; import { fromEvent } from "rxjs"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent implements AfterViewInit, AfterViewChecked { @ViewChild("btn") btnEl: ElementRef; constructor( private readonly zone: NgZone, private readonly renderer: Renderer2 ) {} onClick() { console.log("onClick"); } ngAfterViewInit() { this.setupClickListener(); } ngAfterViewChecked() { console.log("CD performed"); } private setupClickListener() { this.zone.runOutsideAngular(() => { this.setupClickListenerViaNativeAPI(); // this.setupClickListenerViaRenderer(); // this.setupClickListenerViaRxJS(); }); } private setupClickListenerViaNativeAPI() { this.btnEl.nativeElement.addEventListener("click", () => { console.log("onClick"); }); } private setupClickListenerViaRenderer() { this.renderer.listen(this.btnEl.nativeElement, "click", () => { console.log("onClick"); }); } Execution of code outside of the NgZone - using directive While the previous paragraph's solution works well, it is a little verbose. we can encapsulate the logic in an attribute directive, which allows dependency injection to provide easy access to the underlying DOM element (ElementRef token). Then, outside of the NgZone, we can add an event listener and emit an event when it's appropriate:   Click handler outside NgZone Click me!import { Directive, ElementRef, EventEmitter, NgZone, OnDestroy, OnInit, Output, Renderer2 } from "@angular/core"; @Directive({ selector: "[click.zoneless]" }) export class ClickZonelessDirective implements OnInit, OnDestroy { @Output("click.zoneless") clickZoneless = new EventEmitter(); private teardownLogicFn: Function; constructor( private readonly zone: NgZone, private readonly el: ElementRef, private readonly renderer: Renderer2 ) {} ngOnInit() { this.zone.runOutsideAngular(() => { this.setupClickListener(); }); } ngOnDestroy() { this.teardownLogicFn(); } private setupClickListener() { this.teardownLogicFn = this.renderer.listen( this.el.nativeElement, "click", (event: MouseEvent) => { this.clickZoneless.emit(event); } ); } } Execution of code outside of the NgZone - using Event Manager Plugin The directive-based approach has the disadvantage of not being able to be configured for an event type. Thankfully, Angular allows us to build our Event Manager Plugin. In other words, we take control of adding a listener for an event whose name corresponds to the predicate function (the supports method). If a match is found, the addEventListener method is called, allowing us to handle the job. The two methods are part of the user-defined service that is registered as an EVENT MANAGER PLUGINS token provider:   Click handler outside NgZone Click me! import { Injectable } from "@angular/core"; import { EventManager } from "@angular/platform-browser"; @Injectable() export class ZonelessEventPluginService { manager: EventManager; supports(eventName: string): boolean { return eventName.endsWith(".zoneless"); } addEventListener( element: HTMLElement, eventName: string, originalHandler: EventListener ): Function { const [nativeEventName] = eventName.split("."); this.manager.getZone().runOutsideAngular(() => { element.addEventListener(nativeEventName, originalHandler); }); return () => element.removeEventListener(nativeEventName, originalHandler); } } import { NgModule } from "@angular/core"; import { BrowserModule, EVENT_MANAGER_PLUGINS } from "@angular/platform-browser"; import { AppComponent } from "./app.component"; import { ClickZonelessDirective } from "./click-zoneless.directive"; import { ZonelessEventPluginService } from "./zoneless-event-plugin.service"; @NgModule({ imports: [BrowserModule], declarations: [ AppComponent, // ClickZonelessDirective ], bootstrap: [AppComponent], providers: [ { provide: EVENT_MANAGER_PLUGINS, useClass: ZonelessEventPluginService, multi: true } ] }) export class AppModule {} Fortunately, by calling the initialization code from outside the NgZone, we can avoid triggering the change detection process:   3rd party lib initialized outside NgZone Hover me!import { Directive, ElementRef, NgZone, OnInit } from "@angular/core"; import tippy from "tippy.js"; @Directive({ selector: "[appTooltip]" }) export class TooltipDirective implements OnInit { constructor(private readonly zone: NgZone, private readonly el: ElementRef) {} ngOnInit() { this.zone.runOutsideAngular(() => { this.setupTooltip(); }); } private setupTooltip() { tippy(this.el.nativeElement, { content: "Bazinga!" }); } } Conclusion If we find ourselves in a situation where we are performing a task that does not need binding updates in response to a DOM event, we can improve the performance of our application by not triggering an unwanted change detection run Outside of the NgZone, we must be careful when registering an event listener. The most elegant and reusable solution is to use a custom Event Planner Plugin. If we're using a third-party solution that modifies the DOM, we should think about running its initialization code outside of the NgZone.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
10 Executive Dashboard Examples for Consultants and CEOs
10 Executive Dashboard Examples for Consultants and CEOs

There is a principle behind every business. “If you don’t keep track of essentials, you won’t get clear direction, eventually causing your company to stumble.” To manage this scenario,...

How Spatial Data Analysis Improves Healthcare
How Spatial Data Analysis Improves Healthcare

Do you know when geospatial analysis took traction in healthcare? It was when John Snow, a London-based physician, used it to analyze the spread of cholera, which ultimately proved...

4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical
4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical

One interesting aspect you truly love about Power BI, as a CTO, is how it lets you step back and see the bigger picture of your business. Isn’t it? Without getting bogged down in minute...