Skip to main content

How do you implement a custom change detection strategy?

In Angular, you can create a custom change detection strategy, but this is rarely needed, since the standard strategies (Default and OnPush) cover most cases. The basic idea is to use the ChangeDetectorRef interface and control when Angular checks the component.

Main approaches

  1. Using ChangeDetectorRef inside the component
  • You can manually trigger a change check.
ts
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-my', template: '{{ counter }}' }) export class MyComponent { counter = 0; constructor(private cd: ChangeDetectorRef) {} increment() { this.counter++; this.cd.detectChanges(); // manually runs the change check } }
  • Here you control when the check happens, instead of relying on Angular's automatic trigger.
  1. Using detach() and reattach()
  • You can turn off change detection for the component entirely and enable it only on a specific event.
ts
ngOnInit() { this.cd.detach(); // the component is no longer checked automatically } update() { this.counter++; this.cd.reattach(); this.cd.detectChanges(); this.cd.detach(); }
  • This lets you implement your "own strategy", where the check runs only according to your own rules.
  1. Extending the built-in mechanism
  • Angular does not provide a direct way to register a completely new strategy (ChangeDetectionStrategy is an enum), but through ChangeDetectorRef and manual control you can simulate any logic.

In other words, a custom strategy is implemented through manual control of change detection via ChangeDetectorRef, turning off automatic tracking and calling detectChanges() only when needed.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.