DEV Community

Cover image for Angular Change Detection and OnPush Strategy πŸš€
Manoj Prasanna  πŸš€
Manoj Prasanna πŸš€

Posted on

Angular Change Detection and OnPush Strategy πŸš€

In this article, I will delve into the concept of Change Detection and the functionality of the OnPush strategy within the Angular framework.

Understanding Angular Change Detection

Have you ever encountered a scenario where your Angular application required automatic updates upon detecting the necessity for a change? If that's the case, you likely implemented Angular's Change Detection mechanism, specifically the OnPush strategy. This strategy proves to be highly efficient in swiftly detecting changes, particularly for value type.Let jump to understand about this change detections.

While this approach ensures accuracy, it can lead to performance bottlenecks in complex applications

When you make any changes to your model in the application, Anulgar will detect the changes and immediately update the view.Angular's change detection mechanism ensures continuous synchronization (Two way data binding) between the underlying models and their respective views.
Let know about in angular can change as a result of any of the following sceniors.

  • DOM Event

  • AJAX HTTP requests

  • Timers(SetInterval() , SetTimer())

Understaning about the Angular change detaction cycle

Angular's change detection cycle is a critical part of how the framework updates and synchronizes the DOM with your application's data. It's responsible for detecting and propagating changes from your application's data model to the user interface. Understanding the change detection cycle is important for optimizing your application's performance and avoiding unnecessary updates.

Suppose we have a simple Angular component called devCounterComponent that displays a counter value and a button to increment it

import { Component } from '@angular/core';

@Component({
  selector: 'app-dev-counter',
  template: `
    <div>
      <p>Counter: {{ counter }}</p>
      <button (click)="increment()">Increment</button>
    </div>
  `,
})
export class DevCounterComponent {
  counter = 0;

  increment() : void {
    this.counter++;
  }
}
Enter fullscreen mode Exit fullscreen mode

Now, let's follow the change detection cycle with above example.

  1. Initialization:
    When the application starts, Angular initializes the DevCounterComponent.

  2. Rendering Initial View:
    The initial view is rendered, showing the counter value as 0 and the "Increment" button.

  3. Event Handling and Data Binding:
    When the user clicks the "Increment" button, the increment() method is triggered.

  4. Change Detection Triggers:
    The increment() method changes the value of the counter property.

  5. Change Detection Process:
    Angular's change detection system detects the change in the counter property and starts the change detection process.

  6. Checking Components for Changes:
    Angular checks the DevCounterComponent for changes. It compares the new value of the counter property (1) with the previous value (0).

  7. Updating the DOM:
    Since there is a change in the counter property, Angular updates the DOM to reflect the new value. The counter value displayed in the template is now 1.

  8. Child Components:
    In this example, there are no child components, so this step is skipped.

  9. Repeat Process:
    The change detection cycle is complete for now. If another change is triggered (e.g., another button click), the process will repeat.

Let's explore a more complex example involving parent and child components. Suppose we have a ParentComponent that contains two instances of the DevCounterComponent.

import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <div>
      <app-dev-counter></app-dev-counter>
      <app-dev-counter></app-dev-counter>
    </div>
  `,
})
export class ParentComponent {}
Enter fullscreen mode Exit fullscreen mode

But we should still be mindful of performance considerations and use strategies like OnPush change detection when appropriate to optimize their applications.

Certainly, let's delve into the OnPush change detection strategy in Angular. This strategy is a significant aspect of the change detection cycle, and understanding it is essential for effective application development.

Understanding about OnPush Detection Strategy

The "OnPush" change detection strategy is a feature in Angular that optimizes the change detection process by reducing the number of checks and updates made by Angular's change detection mechanism. It is designed to improve the performance of your Angular applications by focusing on components that explicitly indicate when their input properties have changed.
By default, Angular uses the "Default" change detection strategy, where it checks for changes in all components and their templates on every change detection cycle. This can lead to unnecessary checks and updates, impacting performance in larger applications. The "OnPush" strategy provides a way to mitigate this by making components more selective about when they should be checked for changes.

Here is a table summarizing the key differences between the two strategies
Default : Every change detection cycle
OnPush : When inputs or properties change

When to use OnPush

The "OnPush" change detection strategy should be used for components that are not constantly changing. This includes components that

  • Display static data

  • Only receive data from their parent components

  • Do not perform any calculations or transformations on their data

To set the "OnPush" strategy for a component, you specify it in the component's metadata using the changeDetection property. Here's an example

import { Component, Input, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-onpush-dev',
  templateUrl: './onpush-dev.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OnPushDevComponent {
  @Input() data: any;

  constructor(private cdr: ChangeDetectorRef) {}

  // This method marks the component for change detection.
  triggerChangeDetection() {
    this.cdr.markForCheck();
  }

  // Event handler that updates the input property.
  updateData() {
    this.data = { newValue: 'Updated value' };
  }
}

Enter fullscreen mode Exit fullscreen mode

In this example, the component OnPushdevComponent uses the "OnPush" change detection strategy. It has an input property data and a method triggerChangeDetection() that can be used to manually trigger change detection.

Conclusion

The OnPush change detection strategy can be a powerful tool for improving the performance of your Angular applications. However, it is important to use it wisely and to make sure that your components are using immutable data structures. By following these guidelines, you can use the OnPush change detection strategy to optimize your Angular applications and improve their performance.

That’s It!
Thanks for reading the whole story ❀

Top comments (0)