Home > Article > Web Front-end > What is change detection in Angular? Under what circumstances will change detection be triggered?
What is change detection in Angular? The following article will take you through change detection and introduce the circumstances under which change detection will occur. I hope it will be helpful to you!
To put it simply, change detection is used by Angular to detect whether the values bound between the view and the model have changed. When it is detected that the value in the model has changed, it is synchronized to the view. , conversely, when it is detected that the value on the view changes, the corresponding binding function is called back. [Related tutorial recommendations: "angular tutorial"]
That is, the mechanism that keeps model changes consistent with the view. This mechanism is called change detection.
In Angular, developers don’t need to focus on specific DOM updates, just focus on business, because Angular does this part of the work for us.
If we don’t use Angular and develop with native JS, we must update the DOM manually. Let’s look at an example first.
<html> <div id="dataDiv"></div> <button id="btn">updateData</button> <canvas id="canvas"></canvas> <script> let value = 'initialValue'; // initial rendering detectChange(); function renderHTML() { document.getElementById('dataDiv').innerText = value; } function detectChange() { const currentValue = document.getElementById('dataDiv').innerText; if (currentValue !== value) { renderHTML(); } } // Example 1: update data inside button click event handler document.getElementById('btn').addEventListener('click', () => { // update value value = 'button update value'; // call detectChange manually detectChange(); }); // Example 2: HTTP Request const xhr = new XMLHttpRequest(); xhr.addEventListener('load', function() { // get response from server value = this.responseText; // call detectChange manually detectChange(); }); xhr.open('GET', serverUrl); xhr.send(); // Example 3: setTimeout setTimeout(() => { // update value inside setTimeout callback value = 'timeout update value'; // call detectChange manually detectChange(); }, 100); // Example 4: Promise.then Promise.resolve('promise resolved a value').then(v => { // update value inside Promise thenCallback value = v; // call detectChange manually detectChange(); }, 100); // Example 5: some other asynchronous APIs document.getElementById('canvas').toBlob(blob => { // update value when blob data is created from the canvas value = `value updated by canvas, size is ${blob.size}`; // call detectChange manually detectChange(); }); </script> </html>
In the above example, after we update the data, we need to call detectChange() to check whether the data has changed. If the data has changed, the HTML is rendered to reflect the updated data. Of course, in Angular, developers do not need to care about these steps, they only need to update your data, and the DOM will automatically update . This is change detection.
The key to change detection is how to detect with the smallest granularity whether the bound value has changed, and under what circumstances Will it cause the values of these bindings to change?
Let’s look at several scenarios based on daily development.
Scenario 1
Component initialization:
When starting the Angular application, Angular will Load the bootstrap component and trigger ApplicationRef.tick() to invoke change detection and view rendering.
Scenario 2
DOM and BOM events:
DOM eventsOr BOM eventsListeners can update data in Angular components and can also trigger change detection, as shown in the example below.
@Component({ selector: "counter", template: ` Count:{{ count }} <br /> <button (click)="add()">Add</button> `, }) export class CounterComponent { count = 0; constructor() {} add() { this.count = this.count + 1; } }
We bound the count attribute in counter through interpolation expression on the view. When the button is clicked, the value of the count attribute is changed, which causes the bound value to change.
Scenario 3
HTTP data request:
@Component({ selector: "todos", template: ` <li *ngFor="let item of todos">{{ item.titme }}</li> `, }) export class TodosComponent implements OnInit { public todos: TodoItem[] = []; constructor(private http: HttpClient) {} ngOnInit() { this.http.get<TodoItem[]>("/api/todos").subscribe((todos: TodoItem[]) => { this.todos = todos; }); } }
We request this in the todos component The server sends an Ajax request. When the request returns the result, the value of the todos bound in the view will be changed.
Scenario 4
Other macro tasks and micro tasks:
Such as setTimeout() or setInterval(). You can also update data in the callback function of the setTimeout() macroTask.
@Component({ selector: 'app-root', template: '<div>{{data}}</div>'; }) export class AppComponent implements OnInit { data = 'initial value'; ngOnInit() { setTimeout(() => { // user does not need to trigger change detection manually this.data = 'value updated'; }); } }
In actual development, a timer may be called in a certain function to change a bound value.
Another example is Promise.then(). Other asynchronous APIs (such as fetch) return Promise objects, so the then() callback function can also update data.
@Component({ selector: 'app-root', template: '<div>{{data}}</div>'; }) export class AppComponent implements OnInit { data = 'initial value'; ngOnInit() { Promise.resolve(1).then(v => { // user does not need to trigger change detection manually this.data = v; }); } }
Scenario 5
Other asynchronous operations:
ExceptaddEventListener() , setTimeout() and Promise.then(), and other operations that can update data asynchronously. For example WebSocket.onmessage() and Canvas.toBlob().
It is not difficult to find that the above situations have one thing in common, that is, The events that cause the binding value to change are asynchronous events. As long as an asynchronous operation occurs, Angular will think that the state may have changed, and then perform change detection.
Thinking: What other asynchronous events are there?
These cover the most common scenarios in which an application may change data. Whenever Angular detects that data may have changed, it performs change detection, and the result of change detection is that the DOM is updated based on this new data. Angular detects changes in different ways. For component initialization, Angular calls explicit change detection. For asynchronous operations, Angular will use Zone to detect changes where data may be modified and automatically run change detection.
How to subscribe to these asynchronous events? Please look forward to the next article.
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of What is change detection in Angular? Under what circumstances will change detection be triggered?. For more information, please follow other related articles on the PHP Chinese website!