Skip to content

Commit 557b639

Browse files
committed
Add data update scenarios
1 parent 0de8920 commit 557b639

File tree

1 file changed

+53
-2
lines changed

1 file changed

+53
-2
lines changed

Diff for: README.md

+53-2
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@
251251
|243| [Wat is ngzone?](#what-is-ngzone)|
252252
|244| [What is NoopZone?](#what-is-noopzone)|
253253
|245| [How do you create displayBlock components?](#how-do-you-create-displayblock-components)|
254-
|246| [?](#)|
254+
|246| [What are the possible data change scenarios for change detection?](#what-are-the-possible-data-change-scenarios-for-change-detection)|
255255
|247| [?](#)|
256256
|248| [?](#)|
257257
|249| [?](#)|
@@ -3589,7 +3589,58 @@
35893589
35903590
**[⬆ Back to Top](#table-of-contents)**
35913591
3592-
246. ### ?
3592+
246. ### What are the possible data update scenarios for change detection?
3593+
The change detection works in the following scenarios where the data changes needs to update the application HTML.
3594+
1. **Component initialization:** While bootstrapping the Angular application, Angular triggers the `ApplicationRef.tick()` to call change detection and View Rendering.
3595+
2. **Event listener:** The DOM event listener can update the data in an Angular component and trigger the change detection too.
3596+
```js
3597+
@Component({
3598+
selector: 'app-event-listener',
3599+
template: `
3600+
<button (click)="onClick()">Click</button>
3601+
{{message}}`
3602+
})
3603+
export class EventListenerComponent {
3604+
message = '';
3605+
3606+
onClick() {
3607+
this.message = 'data updated';
3608+
}
3609+
}
3610+
```
3611+
3. **HTTP Data Request:** You can get data from a server through an HTTP request
3612+
```js
3613+
data = 'default value';
3614+
constructor(private httpClient: HttpClient) {}
3615+
3616+
ngOnInit() {
3617+
this.httpClient.get(this.serverUrl).subscribe(response => {
3618+
this.data = response.data; // change detection will happen automatically
3619+
});
3620+
}
3621+
```
3622+
4. **Macro tasks setTimeout() or setInterval():** You can update the data in the callback function of setTimeout or setInterval
3623+
```js
3624+
data = 'default value';
3625+
3626+
ngOnInit() {
3627+
setTimeout(() => {
3628+
this.data = 'data updated'; // Change detection will happen automatically
3629+
});
3630+
}
3631+
```
3632+
5. **Micro tasks Promises:** You can update the data in the callback function of promise
3633+
```js
3634+
data = 'initial value';
3635+
3636+
ngOnInit() {
3637+
Promise.resolve(1).then(v => {
3638+
this.data = v; // Change detection will happen automatically
3639+
});
3640+
}
3641+
```
3642+
6. **Async operations like Web sockets and Canvas:** The data can be updated asynchronously using WebSocket.onmessage() and Canvas.toBlob().
3643+
35933644
35943645
**[⬆ Back to Top](#table-of-contents)**
35953646

0 commit comments

Comments
 (0)