Questions
What is change detection and how does it work in Angular?
The Scenario
You are a frontend engineer at a social media company. You are building a new component that displays a real-time feed of data.
The component is not updating as quickly as you would like, and you suspect that the issue might be with the change detection strategy.
The Challenge
Explain what change detection is in Angular and how it works. What are the different change detection strategies, and how would you use them to optimize the performance of the component?
A junior engineer might not be aware of change detection. They might try to solve the problem by manually updating the DOM, which would be a very bad practice.
A senior engineer would know that change detection is a critical part of the Angular framework. They would be able to explain what change detection is and how it works. They would also have a clear plan for how to use the different change detection strategies to optimize the performance of the component.
Step 1: Understand What Change Detection Is
Change detection is the process of detecting when the state of a component has changed and then re-rendering the component to reflect the new state.
Step 2: The Different Change Detection Strategies
| Strategy | Description |
|---|---|
Default | The default change detection strategy. Angular will check for changes on every browser event, timer, and XHR. |
OnPush | A more performant change detection strategy. Angular will only check for changes when an input property of the component changes, or when an event is fired by the component or one of its children. |
Step 3: Choose the Right Tool for the Job
For our use case, we should use the OnPush change detection strategy. This is because we are building a component that displays a real-time feed of data, and we want to make sure that the component is only re-rendered when the data actually changes.
Step 4: Code Examples
Here’s how we can use the OnPush change detection strategy:
import { Component, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'my-component',
template: '...',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
// ...
}By using the OnPush change detection strategy, we can significantly improve the performance of our component.
Practice Question
You have a component that has a lot of input properties that change frequently. Which change detection strategy would be the most appropriate?