Deactivate Angular NgZone Selectively — The Easy Way

Introducing the unpatch directive, a powerful tool for optimizing Angular applications

Generated by MidJourney AI

A fine-grained control over Angular’s change detection mechanism is here and ready to be used!

Signals and change detection optimization is not quite there yet. But even today there are ways to help you manage change detection easily.

The reactive extensions for Angular, RxAngular, provide us with powerful tools to control and optimize our application performance. One of these tools is the unpatch directive.

💡 Note: Open-source tools such as Bit let you share your reusable components across multiple projects with a simple command. Bit comes with an integrated dev environment (compiler, tester, linter, documentation, CI, dev server, and packaging/dependency management/bundler all-in-one) for building apps with Angular.

Learn more here:

Overview | Bit

Generated by MidJourney AI

What is Unpatch Directive?

In Angular, the NgZone service manages the execution of tasks inside or outside Angular’s change detection mechanism. Veteran Angular developers describe this as two zones. By default, Angular runs almost everything inside an Angular Zone, meaning any asynchronous operations like setTimeout, Promise, or any DOM events will trigger Angular’s change detection.

While this default mechanism ensures that the UI is consistently updated with the latest changes, it can lead to performance issues when handling high-frequency events, such as mousemove or scroll. These events can trigger a large number of unnecessary change detection cycles.

This is where the unpatch directive steps in. By using unpatch, we can prevent certain events from triggering change detection — improving performance. The directive can be used on any element to which you apply event bindings.

<button unpatch (click)="triggerSomeMethod($event)">click me</button>

The unpatch directive prevents the ‘click’ event from triggering Angular’s change detection.

Generated by MidJourney AI

How to utilize `unpatch` in your app

Let’s dive into a real-world scenario where unpatch can significantly boost performance. Imagine we’re building a real-time data visualization tool, handling a large number of DOM elements and several high-frequency events like mousemove, scroll, etc.

Initially, we have a component rendering a large dataset in a tabular format. Each row of the table has a hover effect showing additional data.

<div *ngFor="let data of largeDataSet">
<div (mousemove)="showAdditionalData(data)" class="data-row">
<!-- Basic data display -->
</div>
</div>

In this scenario, the mousemove event fires very frequently, triggering change detection for the entire component tree. Even if the additional data doesn’t change, Angular still rerenders the component tree, leading to performance issues.

Now, let’s optimize this with the unpatch directive:

<div *ngFor="let data of largeDataSet">
<div [unpatch]="['mousemove']" (mousemove)="showAdditionalData(data)" class="data-row">
<!-- Basic data display -->
</div>
</div>

By using unpatch, we’re instructing Angular not to run change detection every time the ‘mousemove’ event fires.

Generated by MidJourney AI

Kanban Board

Imagine a Kanban board application where users can drag and drop tasks between different columns.

<div class="task" 
(dragstart)="dragStart($event, task)"
(dragover)="dragOver($event)"
(drop)="drop($event, column)">
<!-- Task display -->
</div>

Here, the dragstart, dragover, and drop events are firing when a user drags a task and drops it onto another column. Each of these events triggers Angular’s change detection, which can lead to performance issues, especially with a large number of tasks.

Now, let’s optimize this with the unpatch directive:

<div class="task" 
[unpatch]="['dragstart', 'dragover', 'drop']"
(dragstart)="dragStart($event, task)"
(dragover)="dragOver($event)"
(drop)="drop($event, column)">
<!-- Task display -->
</div>

With the unpatch directive, the dragstart, dragover, and drop events will no longer trigger Angular’s change detection. As a result, the performance of the application can significantly improve when users are frequently dragging and dropping tasks.

However, please note that you would need to manually trigger change detection if any of these events cause changes that should be reflected in the UI!

Angular’s ChangeDetectorRef service allows you to manually run change detection on a component and its child components. You can use its detectChanges method to manually trigger change detection:

constructor(private changeDetector: ChangeDetectorRef) {}

drop(event: DragEvent, column: Column) {
// logic

// manually trigger change detection
this.changeDetector.detectChanges();
}

The unpatch directive provided by the RxAngular library is a powerful tool for optimizing Angular applications. By preventing unnecessary change detection cycles, it helps to improve the performance and responsiveness of applications.

Make sure to also check out other goodies that RxAngular offers.

Build Angular Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Introduction to Angular | Bit

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

Learn more:


Deactivate Angular NgZone Selectively — The Easy Way was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Daniel Glejzner

Introducing the unpatch directive, a powerful tool for optimizing Angular applications

Generated by MidJourney AI

A fine-grained control over Angular's change detection mechanism is here and ready to be used!

Signals and change detection optimization is not quite there yet. But even today there are ways to help you manage change detection easily.

The reactive extensions for Angular, RxAngular, provide us with powerful tools to control and optimize our application performance. One of these tools is the unpatch directive.

💡 Note: Open-source tools such as Bit let you share your reusable components across multiple projects with a simple command. Bit comes with an integrated dev environment (compiler, tester, linter, documentation, CI, dev server, and packaging/dependency management/bundler all-in-one) for building apps with Angular.

Learn more here:

Overview | Bit

Generated by MidJourney AI

What is Unpatch Directive?

In Angular, the NgZone service manages the execution of tasks inside or outside Angular’s change detection mechanism. Veteran Angular developers describe this as two zones. By default, Angular runs almost everything inside an Angular Zone, meaning any asynchronous operations like setTimeout, Promise, or any DOM events will trigger Angular's change detection.

While this default mechanism ensures that the UI is consistently updated with the latest changes, it can lead to performance issues when handling high-frequency events, such as mousemove or scroll. These events can trigger a large number of unnecessary change detection cycles.

This is where the unpatch directive steps in. By using unpatch, we can prevent certain events from triggering change detection — improving performance. The directive can be used on any element to which you apply event bindings.

<button unpatch (click)="triggerSomeMethod($event)">click me</button>

The unpatch directive prevents the 'click' event from triggering Angular's change detection.

Generated by MidJourney AI

How to utilize `unpatch` in your app

Let’s dive into a real-world scenario where unpatch can significantly boost performance. Imagine we're building a real-time data visualization tool, handling a large number of DOM elements and several high-frequency events like mousemove, scroll, etc.

Initially, we have a component rendering a large dataset in a tabular format. Each row of the table has a hover effect showing additional data.

<div *ngFor="let data of largeDataSet">
<div (mousemove)="showAdditionalData(data)" class="data-row">
<!-- Basic data display -->
</div>
</div>

In this scenario, the mousemove event fires very frequently, triggering change detection for the entire component tree. Even if the additional data doesn’t change, Angular still rerenders the component tree, leading to performance issues.

Now, let’s optimize this with the unpatch directive:

<div *ngFor="let data of largeDataSet">
<div [unpatch]="['mousemove']" (mousemove)="showAdditionalData(data)" class="data-row">
<!-- Basic data display -->
</div>
</div>

By using unpatch, we're instructing Angular not to run change detection every time the 'mousemove' event fires.

Generated by MidJourney AI

Kanban Board

Imagine a Kanban board application where users can drag and drop tasks between different columns.

<div class="task" 
(dragstart)="dragStart($event, task)"
(dragover)="dragOver($event)"
(drop)="drop($event, column)">
<!-- Task display -->
</div>

Here, the dragstart, dragover, and drop events are firing when a user drags a task and drops it onto another column. Each of these events triggers Angular’s change detection, which can lead to performance issues, especially with a large number of tasks.

Now, let’s optimize this with the unpatch directive:

<div class="task" 
[unpatch]="['dragstart', 'dragover', 'drop']"
(dragstart)="dragStart($event, task)"
(dragover)="dragOver($event)"
(drop)="drop($event, column)">
<!-- Task display -->
</div>

With the unpatch directive, the dragstart, dragover, and drop events will no longer trigger Angular's change detection. As a result, the performance of the application can significantly improve when users are frequently dragging and dropping tasks.

However, please note that you would need to manually trigger change detection if any of these events cause changes that should be reflected in the UI!

Angular’s ChangeDetectorRef service allows you to manually run change detection on a component and its child components. You can use its detectChanges method to manually trigger change detection:

constructor(private changeDetector: ChangeDetectorRef) {}

drop(event: DragEvent, column: Column) {
// logic

// manually trigger change detection
this.changeDetector.detectChanges();
}

The unpatch directive provided by the RxAngular library is a powerful tool for optimizing Angular applications. By preventing unnecessary change detection cycles, it helps to improve the performance and responsiveness of applications.

Make sure to also check out other goodies that RxAngular offers.

Build Angular Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Introduction to Angular | Bit

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

Learn more:


Deactivate Angular NgZone Selectively — The Easy Way was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Daniel Glejzner


Print Share Comment Cite Upload Translate Updates
APA

Daniel Glejzner | Sciencx (2023-05-18T09:21:24+00:00) Deactivate Angular NgZone Selectively — The Easy Way. Retrieved from https://www.scien.cx/2023/05/18/deactivate-angular-ngzone-selectively-the-easy-way-2/

MLA
" » Deactivate Angular NgZone Selectively — The Easy Way." Daniel Glejzner | Sciencx - Thursday May 18, 2023, https://www.scien.cx/2023/05/18/deactivate-angular-ngzone-selectively-the-easy-way-2/
HARVARD
Daniel Glejzner | Sciencx Thursday May 18, 2023 » Deactivate Angular NgZone Selectively — The Easy Way., viewed ,<https://www.scien.cx/2023/05/18/deactivate-angular-ngzone-selectively-the-easy-way-2/>
VANCOUVER
Daniel Glejzner | Sciencx - » Deactivate Angular NgZone Selectively — The Easy Way. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/05/18/deactivate-angular-ngzone-selectively-the-easy-way-2/
CHICAGO
" » Deactivate Angular NgZone Selectively — The Easy Way." Daniel Glejzner | Sciencx - Accessed . https://www.scien.cx/2023/05/18/deactivate-angular-ngzone-selectively-the-easy-way-2/
IEEE
" » Deactivate Angular NgZone Selectively — The Easy Way." Daniel Glejzner | Sciencx [Online]. Available: https://www.scien.cx/2023/05/18/deactivate-angular-ngzone-selectively-the-easy-way-2/. [Accessed: ]
rf:citation
» Deactivate Angular NgZone Selectively — The Easy Way | Daniel Glejzner | Sciencx | https://www.scien.cx/2023/05/18/deactivate-angular-ngzone-selectively-the-easy-way-2/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.