Table of Contents
#What is change detection?
Under what circumstances will change detection be caused?
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?

Dec 13, 2022 pm 08:06 PM
angular Change detection

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Let's talk about metadata and decorators in Angular Let's talk about metadata and decorators in Angular Feb 28, 2022 am 11:10 AM

This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

Angular + NG-ZORRO quickly develop a backend system Angular + NG-ZORRO quickly develop a backend system Apr 21, 2022 am 10:45 AM

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

See all articles