Home > Web Front-end > JS Tutorial > What is change detection in Angular? Under what circumstances will change detection be triggered?

What is change detection in Angular? Under what circumstances will change detection be triggered?

青灯夜游
Release: 2022-12-13 20:06:00
forward
2086 people have browsed it

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!

What is change detection in Angular? Under what circumstances will change detection be triggered?

#What is change detection?

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 = &#39;initialValue&#39;;
    // initial rendering
    detectChange();

    function renderHTML() {
      document.getElementById(&#39;dataDiv&#39;).innerText = value;
    }

    function detectChange() {
      const currentValue = document.getElementById(&#39;dataDiv&#39;).innerText;
      if (currentValue !== value) {
        renderHTML();
      }
    }

    // Example 1: update data inside button click event handler
    document.getElementById(&#39;btn&#39;).addEventListener(&#39;click&#39;, () => {
      // update value
      value = &#39;button update value&#39;;
      // call detectChange manually
      detectChange();
    });

    // Example 2: HTTP Request
    const xhr = new XMLHttpRequest();
    xhr.addEventListener(&#39;load&#39;, function() {
      // get response from server
      value = this.responseText;
      // call detectChange manually
      detectChange();
    });
    xhr.open(&#39;GET&#39;, serverUrl);
    xhr.send();

    // Example 3: setTimeout
    setTimeout(() => {
      // update value inside setTimeout callback
      value = &#39;timeout update value&#39;;
      // call detectChange manually
      detectChange();
    }, 100);

    // Example 4: Promise.then
    Promise.resolve(&#39;promise resolved a value&#39;).then(v => {
      // update value inside Promise thenCallback
      value = v;
      // call detectChange manually
      detectChange();
    }, 100);

    // Example 5: some other asynchronous APIs
    document.getElementById(&#39;canvas&#39;).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>
Copy after login

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.

Under what circumstances will change detection be caused?

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;
  }
}
Copy after login

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;
      });
    }
  }
Copy after login

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: &#39;app-root&#39;,
  template: &#39;<div>{{data}}</div>&#39;;
})
export class AppComponent implements OnInit {
  data = &#39;initial value&#39;;

  ngOnInit() {
    setTimeout(() => {
      // user does not need to trigger change detection manually
      this.data = &#39;value updated&#39;;
    });
  }
}
Copy after login

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: &#39;app-root&#39;,
  template: &#39;<div>{{data}}</div>&#39;;
})
export class AppComponent implements OnInit {
  data = &#39;initial value&#39;;

  ngOnInit() {
    Promise.resolve(1).then(v => {
      // user does not need to trigger change detection manually
      this.data = v;
    });
  }
}
Copy after login

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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template