Home > Web Front-end > JS Tutorial > body text

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

青灯夜游
Release: 2022-12-13 20:06:00
forward
1873 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.


  
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 }}
    
`, }) 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: ` 
  • {{ item.titme }}
  • `, }) export class TodosComponent implements OnInit { public todos: TodoItem[] = []; constructor(private http: HttpClient) {} ngOnInit() { this.http.get("/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: 'app-root',
      template: '
    {{data}}
    '; }) export class AppComponent implements OnInit { data = 'initial value'; ngOnInit() { setTimeout(() => { // user does not need to trigger change detection manually this.data = 'value updated'; }); } }
    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: 'app-root',
      template: '
    {{data}}
    '; }) 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; }); } }
    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
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!