This page looks best with JavaScript enabled

How Change Detection Works In Angular

 ·  ☕ 5 min read  ·  ✍️ Adesh

What is change detection in Angular?

Change Detection means updating the DOM whenever data is changed. Angular can detect when component data changes, and then automatically re-render the view to reflect that change.

Any component’s state change is triggered by these three things:-

  • Events - click, submit….
  • HTTP API - any interaction with server
  • Timers - setTimeout(), setInterval()

There needs to be a mechanism to detect component state changes, and re-rendered the view as needed. Let’s see how it works.

Angular Default Change Detection Strategy

By default Angular uses the ChangeDetectionStrategy.Default change detection strategy.

The default strategy of change detection in Angular starts at the top at its root component and goes down the component tree, checking every component even if it has not changed. It compares the current value of the property used in the template expression with the previous value of that property.

Let’s have a look at our user component.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

  @Input() user;

  ngOnInit() { }

  get runChangeDetection() {
    console.log('Running change detection');
    return true;
  }
}
1
2
3
4
<h2>
  Hello {{user.firstname}} {{user.lastname}} !
</h2>
{{runChangeDetection}}

Place this user component inside the app component. Here is our app component.

1
2
<app-user [user]='admin'></app-user>
<button (click)='changeName()'>Change Name</button>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  admin: any;

  ngOnInit() {
    this.admin = {
      firstname: 'James',
      lastname: 'Copper'
    };
  }

  changeName() {
    this.admin.firstname = 'Nicole';
  }
}

Let me walk through the above code. In the above code, I have created a simple user component with a @Input() parameter user, and a method runChangeDetection().

In the app component, I have placed this user component as a child component and setting the user attribute of <app-user></app-user> to admin object of app component. There is a button, where we are changing the firstname of admin object on its click event.

As soon as we click the button, and change the property of our admin object, Angular will trigger the change detection to make sure the DOM is sync with the object, which is admin in this case. For each property changes, Angular change detector will traverse the component tree and update the DOM.

On every click, there is a console log like below:-

change detection in angular

Now, as you see, every time you update the object property, Angular will trigger change detection. As a result, the change detector will traverse through the whole component tree, starting from root to the bottom. Traversing and detecting the change is a heavy process, which may cause performance degradation of application.

What if, we have thousands of components in tree, and even a single update in object property trigger the change detection. Then change detector has to traverse all those thousands of components in the tree in order to make DOM updated as required. This may lead to a performance problem.

Although Angular is very fast, as your app grows, Angular will have to work harder to keep track of all the changes. What if we could help Angular and give it a better indication of when to check our components?

OnPush Change Detection Strategy

Angular offers another change detection strategy: it’s called OnPushand it can be defined on any component.

With this strategy, the template of the component will only be checked in 2 cases:

  • one of the inputs of the component changed (to be more accurate, when the reference of one of the inputs changes);
  • an event handler of the component was triggered.

This can be very convenient when the template of a component only depends on its inputs, and can give a serious boost to your application.

We can set the ChangeDetectionStrategy of our component to ChangeDetectionStrategy.OnPush

Let’s get back to our <app-user> component, and see how to implement OnPush change detection. This is very simple and straight forward step.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import { Component, OnInit, Input, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserComponent implements OnInit {

  @Input() user;

  ngOnInit() { }

  get runChangeDetection() {
    console.log('Running change detection from user component');
    return true;
  }
}

I have added changeDetection to onPush on line 7, keep rest of the code same. Now, click on button and see the effects.

There is no name change and no console log as well. You might be wondering, why this is not happening. The reason being is that, on implementing the onPush change detection, Angular will run the change detector only when the reference passed to the component is changed instead of some property changed in the object.

So, here in our previous code in app component changeName() event, we are just changing the object property, not changing the reference.

So, as per onPush strategy, it will not trigger the change detection, and no DOM will be updated. To fix this issue, we have to change our code like below:

1
2
3
4
5
6
changeName() {
    this.admin = {
      firstname: 'Nicole',
      lastname: 'Kooper'
    };
  }

In the above code snippet, we are changing the reference of the object instead of just changing just one property. Now when you run the application, you will find on the click of the button that the DOM is being updated with the new value.

Reference

Angular docs - change detection

Further Reading

Getting Started With Docker

Docker Introduction With Its Architecture And Components

Testing Angular App With Karma And Jasmine

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect