Originally published by Adesh at zeptobook.com
Today I would like to discuss about change detection in Angular. Change detection is crucial to understand in order to keep Angular application’s performance better. In a small Angular application, you will not see any significant performance boost using change detection. But, in larger applications having thousands of components with complex component tree structure, will have performance boost using change detection.
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:-
There need to be a mechanism to detect component state changes, and re-rendered the view as needed. Here is where change detection comes into play.
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.
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;
}
}
<h2>
Hello {{user.firstname}} {{user.lastname}} !
</h2>
{{runChangeDetection}}
Place this user component inside the app component. Here is our app component.
<app-user [user]=‘admin’></app-user>
<button (click)=‘changeName()’>Change Name</button>
import { Component, OnInit } from ‘@angular/core’;@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:-
Now, as you see, every time you change the object property, Angular will trigger change detection. As a result, change detector will traverse through the whole component tree, starting from root to the bottom. Traversing and change detection is a heavy process, which may cause performance degradation of application.
What if, we have thousands of components in tree, and even a single change in object property trigger the change detection. Then change detector has to traverse all those thousands components in tree in order to make DOM updated as required. This may lead to 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?
Angular offers another change detection strategy: it’s called OnPush
and it can be defined on any component.
With this strategy, the template of the component will only be checked in 2 cases:
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.
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.
this.admin.firstname = ‘Nicole’;
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:
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.
In this blog, we learned about basics of Angular change detection and how can we accomplish it in our components. OnPush change detection strategy can boost performance of any large scale application. In the upcoming posts, I will try to cover other aspects of Change detection as well.
Originally published by Adesh at zeptobook.com
==========================================
Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter
☞ Angular 8 (formerly Angular 2) - The Complete Guide
☞ Complete Angular 8 from Zero to Hero | Get Hired
☞ Learn and Understand AngularJS
☞ The Complete Angular Course: Beginner to Advanced
☞ Angular Crash Course for Busy Developers
☞ Angular Essentials (Angular 2+ with TypeScript)
☞ Angular (Full App) with Angular Material, Angularfire & NgRx
☞ Angular & NodeJS - The MEAN Stack Guide
#angular #web-development