Understanding Angular Change Detection: Strategies and Best Practices

A strong framework for creating dynamic web apps is Angular. One of its core features that ensures applications remain interactive and responsive is Angular Change Detection. This mechanism ensures that the view reflects updates in the application’s state. However, the default approach can sometimes lead to performance bottlenecks, especially in large applications. In this blog, we will explore different change detection strategies, including the popular OnPush strategy.

What is Angular Change Detection?

Angular Change Detection refers to the process by which the framework checks the component tree to see if any data has changed and updates the view accordingly. This process involves checking the component’s model or state, comparing it with the previous state, and if there are any changes, updating the DOM to reflect the new state.

Angular provides a default Angular Change Detection mechanism and also allows developers to customize this behavior using different strategies, the most commonly used being OnPush.

The Two Main Change Detection Strategies in Angular

Angular offers two change detection strategies:

  1. Default Change Detection (ChangeDetectionStrategy.Default)
  2. OnPush Change Detection (ChangeDetectionStrategy.OnPush)

Let’s take a deeper look at both strategies:

🔶 Default Change Detection Strategy

By default, Angular uses ChangeDetectionStrategy.Default for all components. This strategy runs Angular Change Detection for all components in the application every time an event or action occurs that could potentially modify the application’s state. This includes user events, HTTP requests, timers, or subscriptions to observables.

How it Works:

🔹When an event occurs (such as a button click or HTTP response), Angular runs Angular Change Detection from the top of the component tree down to the affected component.
🔹It checks every component and updates the view if any bound properties have changed.
🔹This approach can be performance-intensive, especially for large applications with deep component trees or frequent state changes.

When to Use Default Strategy:

🔹Default Angular Change Detection is suitable for smaller applications or components where performance is not a concern.
🔹It is also useful when you want to ensure that the view is always in sync with the model, no matter how complex the state is.

Drawback:

🔹In large applications, frequent checks on all components can lead to performance issues as Angular Change Detection needs to perform checks on all components in the component tree.

Example:

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  changeDetection: ChangeDetectionStrategy.Default
})
export class ChildComponent {
  @Input() data: any;
}

🔶 OnPush Change Detection Strategy

The OnPush strategy is an optimization technique that reduces the frequency of Angular Change Detection checks. When using OnPush, Angular will only check a component for changes if one of the following conditions is met:

  1. Input Properties Change: If the component receives new inputs, Angular will check for changes.
  2. Events Inside the Component: If an event (like a button click or a form submission) triggers a change in the component, Angular will perform change detection for that component.
  3. Observable Data: If a component subscribes to an observable and the observable emits a new value, Angular will perform Angular Change Detection for the component.

With OnPush, Angular does not perform change detection on the component unless one of the above conditions is satisfied, reducing the overall change detection checks.

How it Works:

🔹OnPush triggers Angular Change Detection only when there’s a change in the component’s input properties, user-triggered events, or observable data.
🔹If none of these conditions occur, Angular will skip change detection for that component.
🔹This can lead to significant performance improvements, especially for large applications with immutable data and few updates to the component tree.

When to Use OnPush:

🔹OnPush is suitable for applications with immutable data or where most components don’t change their inputs frequently.
🔹It is beneficial for large applications or components that rely heavily on observables or do not require frequent updates.

Example:

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

Advantages of OnPush:

🔹Reduced Performance Overhead: Since only components with new input properties or changes in observables are checked, the number of checks is greatly reduced.
🔹Faster Rendering: The application is more responsive because change detection is run less frequently.

Related read: Breaking Down Angular Change Detection System

Get the Best Angular Development Solutions – Contact Us!

🔶 When to Choose OnPush vs Default

While OnPush offers better performance, it may not always be the right choice depending on your application’s requirements. Let’s compare both strategies in different use cases:

Default Strategy is better suited when:

🔹Your application is simple, and performance is not a concern.
🔹You need to ensure that all components are always in sync with the data.
🔹The component tree is shallow, and change detection won’t cause a performance issue.

OnPush Strategy is better suited when:

🔹Your application is complex with many components.
🔹You are working with immutable data, and you want Angular to detect changes only when the inputs change.
🔹You are using observables and want Angular to run change detection only when the data changes.
🔹You want to optimize for performance by reducing unnecessary checks.

🔶 Manual Change Detection (ChangeDetectorRef)

In some situations, you might need more control over when change detection occurs. Angular provides the ChangeDetectorRef service, which allows you to manually trigger change detection.

Methods of ChangeDetectorRef:

➡️ detectChanges(): Change detection for the present component and its offspring is manually triggered. This method forces Angular to check the component for changes even if it’s using OnPush strategy.
➡️ markForCheck(): Marks the current component for checking during the next change detection cycle. This is useful when you want Angular to check the component even if it’s using OnPush strategy but want to wait for the next cycle.
➡️ detach(): Detaches the change detector for the current component from the change detection tree. After detaching, Angular will no longer check the component for changes until it is reattached using reattach().
➡️ reattach(): Reattaches the change detector that was previously detached, allowing Angular to check the component again for changes.

These methods give you more fine-grained control over the change detection cycle and can help optimize performance or ensure that your component is updated in response to specific changes.

Example:

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  updateData(newData) {
  this.data = newData;
  this.cdr.markForCheck(); // Manually trigger change detection
 }
}

Methods in Detail:

🔹detectChanges():

Forces change detection for the component and its children immediately. This method is useful when you need to update the view after a direct change in the component.

Example:

 this.cdr.detectChanges();

🔹markForCheck():

Tells Angular to check the component in the next change detection cycle. This is especially useful when you have an OnPush strategy but still want Angular to perform change detection due to external factors like observables.

Example:

 this.cdr.markForCheck();

🔹detach():

Detaches the component from the change detection tree. This stops Angular from checking the component for changes, which can be beneficial in certain scenarios like optimizing performance in large lists or complex components.

Example:

this.cdr.detach();

🔹reattach():

Reattaches the component to the change detection tree after it has been detached, so Angular can start checking it for changes again.

Example:

 this.cdr.reattach();
coma

Conclusion

Angular Change Detection strategies provide powerful tools for optimizing the performance of your application. The Default strategy is convenient and works for smaller applications, but it can cause performance issues in large applications. The OnPush strategy helps reduce unnecessary checks and improves performance, making it ideal for complex applications with immutable data.

By understanding and choosing the appropriate Angular Change Detection strategy based on your application’s needs, you can ensure that your Angular app is not only functional but also efficient and responsive.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?