Angular & Signals (283 Qs)•Part 9: NgModules, Providers, NgZone & Injector Hierarchies (213 - 255)
What are the possible data update scenarios for change detection?
The change detection works in the following scenarios where the data changes needs to update the application HTML.
- Component initialization: While bootstrapping the Angular application, Angular triggers the
ApplicationRef.tick()to call change detection and View Rendering. - Event listener: The DOM event listener can update the data in an Angular component and trigger the change detection too.
js
@Component({
selector: 'app-event-listener',
template: `
<button (click)="onClick()">Click</button>
{{message}}`
})
export class EventListenerComponent {
message = '';
onClick() {
this.message = 'data updated';
}
}
- HTTP Data Request: You can get data from a server through an HTTP request
js
data = 'default value';
constructor(private httpClient: HttpClient) {}
ngOnInit() {
this.httpClient.get(this.serverUrl).subscribe(response => {
this.data = response.data; // change detection will happen automatically
});
}
- Macro tasks setTimeout() or setInterval(): You can update the data in the callback function of setTimeout or setInterval
js
data = 'default value';
ngOnInit() {
setTimeout(() => {
this.data = 'data updated'; // Change detection will happen automatically
});
}
- Micro tasks Promises: You can update the data in the callback function of promise
js
data = 'initial value';
ngOnInit() {
Promise.resolve(1).then(v => {
this.data = v; // Change detection will happen automatically
});
}
- Async operations like Web sockets and Canvas: The data can be updated asynchronously using WebSocket.onmessage() and Canvas.toBlob().