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.
@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
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
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
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().
Read more
November 04, 2022
AngularNovember 03, 2022
AngularOctober 31, 2022
Angular