WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Angular · Advanced · question 42 of 100

How do you implement custom change detection in Angular, and what are the benefits?

📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

Custom change detection in Angular is implemented using the ‘ChangeDetectionStrategy‘ enum and the ‘ChangeDetectorRef‘ service. There are two main strategies for change detection in Angular: ‘Default‘ and ‘OnPush‘. The default strategy checks for changes every time something happens in your application, such as events, HTTP requests, or timers. On the other hand,‘OnPush‘ strategy only checks for changes when specific events occur, like input value changes or when the change detector is manually triggered.

To implement custom change detection, follow these steps:

**Step 1**: Change the Change Detection Strategy to ‘OnPush‘

Set the change detection strategy of a component to ‘OnPush‘ in the ‘@Component‘ metadata. By doing this, you tell Angular to only check for changes when certain conditions occur.

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

@Component({
  selector: 'app-custom',
  template: `
    <p>{{value}}</p>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CustomComponent {
  @Input() value: string;
}

**Step 2**: Inject the ‘ChangeDetectorRef‘

Inject the ‘ChangeDetectorRef‘ into the component’s constructor. This will give you an object that you can use to control when the change detection should run.

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

@Component({
  selector: 'app-custom',
  template: `
    <p>{{value}}</p>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CustomComponent {
  @Input() value: string;

  constructor(private cdr: ChangeDetectorRef) {}
}

**Step 3**: Manually trigger change detection

You can now manually run the change detector by calling ‘markForCheck()‘ or ‘detectChanges()‘ methods on the ‘ChangeDetectorRef‘ instance.

For instance, assume you have an observable updating the component value. Then you can trigger change detection inside the subscription like this:

import { Component, Input, ChangeDetectionStrategy, ChangeDetectorRef, OnDestroy } from '@angular/core';
import { Observable, Subscription } from 'rxjs';

@Component({
  selector: 'app-custom',
  template: `
    <p>{{value}}</p>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CustomComponent implements OnDestroy {
  @Input() value: string;
  private valueUpdate$: Observable<string>;
  private valueUpdateSubscription?: Subscription;

  constructor(private cdr: ChangeDetectorRef) {
    this.valueUpdate$ = ...; // Initialize your observable
    this.valueUpdateSubscription = this.valueUpdate$.subscribe(newValue => {
      this.value = newValue;
      this.cdr.markForCheck(); // Trigger change detection
    });
  }

  ngOnDestroy() {
    // Clean up the subscription to avoid memory leaks
    this.valueUpdateSubscription?.unsubscribe();
  }
}

**Benefits**:

1. **Performance**: The ‘OnPush‘ strategy improves the performance of your application, as it reduces the number of checks that Angular has to perform. This is especially beneficial for large applications with complex and nested components.

2. **Control**: Using the ‘OnPush‘ strategy gives you more control over when change detection occurs in your components, allowing you to optimize for various application-specific scenarios.

3. **Predictable**: Choosing when the change detection runs can make the data flow in your application more predictable and easier to understand, especially during debugging and data flow related issues.

To sum it up, implementing custom change detection in Angular using the ‘OnPush‘ strategy can significantly improve your application’s performance and provide better control over the change detection process. It is especially helpful in large and complex applications where performance optimizations play a vital role in the overall user experience.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Angular interview — then scores it.
📞 Practice Angular — free 15 min
📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

All 100 Angular questions · All topics