Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Angular Change Detection Strategy: OnPush & Default Strategies

Updated on 17 November, 2022

6.61K+ views
9 min read

Change detection is referred to as the mechanism that checks against the current state to that of the new state. Any difference between the two states suggests that there are changes that need to be updated. It means that the view has to be updated with the change in data.

Any change that occurs in the components during a change in the app is detected through Angular 2+. Whenever a model is changed, the associated changes are detected by angular and the views are updated immediately. This change is referred to as the change detection in angular. 

Check out our free courses to get an edge over the competition.

The change can be the result of data received from network requests or occur through a user event. With the increasing size of the app, more work has to be performed by the method of change detection. Angular detection is necessary to keep in sync between the underlying views and the corresponding models.

The change in the angular model may be due to any of the following:

  • DOM events (click, hover over, etc.)
  • AJAX requests
  • Timers (setTimer(), setInterval())

Prerequisites

For getting a hold of this article you might have to be familiar with the concepts of angular components. Also, the concepts of value types and reference types might be helpful in understanding the article.

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

Change Detection in Angular

The change detection in angular is done in two steps with the first one being the updating of the application model through the developer. It can be preceded either through emitting an event or through the change in the property of a component. The second step i.e. the angular’s job of reflecting the model. It detects if any new data is pushed into the component explicitly. This can be done either through a component or an Observable subscribed to using the async pipe.

Therefore, the two steps are:

  • Update the application model (developer);
  • Reflect the state of the model in the view (Angular).

Check out upGrad’s Java Bootcamp.  

Change detection in angular detects changes of common browser events like mouse clicks, HTTP requests, and other types of events. Once the change is detected it is then decided whether the update of the view is required or not.

Change Detection Strategies

Two angular change detection strategies are present which are the default one and the onPush.

The default strategy

  • The changes on a model are monitored by angular to make sure that all the changes in the model are captured. The differences between the new and the previous state are checked by angular.
  • For a view to be updated, the angular should have access to the new value which is then compared to the old value. Based on this the decision is made whether to update the view or not.
  • Therefore, in a default strategy, the angular revolves around the question of whether there are any changes in the value.
  • There is no assumption as to where the components depend upon. It is a conservative strategy that will check anytime there is an associated change. Checks will be performed over any browser events, times, promises, and XHR’s.
  • The strategy might be a problematic one when big applications are to be considered with many components. 
  • By default, it uses the ChangeDetectionStrategy.Default strategy.

Overriding the default mechanisms of the browser

  • Several low-level APIs will be patched up by angular at the startup time. These APIs may be addEventListener; a browser function that is used for registering browsing events. 
  • The addEventListener will be replaced by angular with a newer version performing like the earlier version.
  • More functionality is added to the event handler by the addEventListener new version. The UI is updated after running the performance check by angular.

Working

A library that is shipped with Zone.js does the low-level patching of browser API. 

  • The zone is defined as the execution content under multiple JVM execution turns. Extra functionality can be added to a browser through this mechanism. The zones are used internally by angular to detect any changes and trigger the detection. 
  • There are normally three phases in a zone, i.e. it is stable at the start, becomes unstable if any task runs in the zone, and it becomes stable once the task is completed.
  • Browser mechanism that is patched up to support the detection in change are:
  1. browser events such as click, etc.
  2. setInterval()and setTimeout()
  3. Requests of Ajax HTTP
  • To trigger change detection in angular, Zone.js is used to patch several APIs of another browser like Websockets. 
  • A limitation to this method is: if Zone.js doesn’t support the browser API, then there will be no trigger during change detection.

How does angular change detection work when change detection is triggered?

The triggered changes are detected through a change detector. This change detector is created during the startup time of the application. An example of the TodoItem component can be considered. An event will be emitted on receiving an object Todo by the component if the status of the todo is toggled. Learn more on how to run angular projects.

Working of the default change detection mechanism

The mechanism of change detection is a simple one. In each expression, the value that is current to the property is compared to the value of that property in the previous state in the expression. 

  • Having a difference in the value of the property will set the value to true of isChanged. 

1. OnPush strategy

  • On using the onPush strategy, the angular need not have to perform any guess on when the check has to be performed. 
  • Based on the change in the input reference, or events triggered by the components themselves, the angular will perform the check for changes.
  • Also, the angular can be explicitly asked to perform the check for changes. This is done through the method of componentRef.markForCheck(). 
  • The components during this strategy will depend only on its inputs. Change detection strategy will be performed only when:
  • There is a change in the input reference.
  • There are associated changes in the components of the model or any of its children.
  • When explicit change detection has to be performed. 
  • When an async pipe in the view is used.
  • Compared to the default strategy, the onpush strategy mainly revolves around two questions which are:
  • Is there any change in the reference type?
  • If there are changes in the reference of the reference type, then are there any changes in the values of the heap memory?
  • It prevents unnecessary checks over the components and also over the child components.

Implementing the onPush Strategy for a Component

Only when a new reference is passed as @Input() value, it triggers change detection. The values may be primitive types like numbers, booleans, string, and null. Arrays and objects can also be used. Modified objects or arrays cannot be used for triggering change detection on an onPush component as a new reference is not created for them. Therefore, a new object or an array reference is to be passed to trigger the detector detecting the change.

To avoid bugs in the method of change detection methods, the application can be built using onPush change detection everywhere through the use of immutable objects and lists. Modification of immutable objects can be done through the creation of a new object reference and hence:

  • For every change, the onPush change detection is triggered.
  • A new object reference is always created which prevents the cause of bugs.

In such cases, the Immutable.js can be used as it contains immutable data structures for objects (Map) and lists (List).

  • Adding the changeDetection parameter in the component annotation will implement the onPush strategy. Instead of passing new references every time, the ChangeDetectorRef can also be used for complete control.

ChangeDetectorRef.detectChanges() 

  • The method of change detection can be attached or detached manually with methods of detach and reattach in the changeDetectorRef.

ChangeDetectorRef.detach() and ChangeDetectorRef.reattach()

Immutable.js

When using the onPush strategy for change detection, it is always a good idea if immutability is enforced.  In such cases, Immutable.js is used. 

The immutable.js is a library created for incorporating immutability in JavaScript along with immutable data structures like List, Stack, and Map.

To add Immutable.js in the projects, the following command has to be used in the terminal. Learn more about angular projects.

$ npm install immutable –save

To import the data structures from Immutable.js, the following command has to be used. The command shows importing only the List, and Map data structures in this case.

import {Map, List} from ‘immutable’;

An array can also be used.

Also if Immutable.js is used, a few drawbacks are associated with it.

  • Using the API is a bit cumbersome.
  • Interfaces cannot be implemented to the data model as the library Imutable.js doesn’t support any interfaces.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Summary

The article introduced you to the mechanism of change detection and the strategies. Angular will perform change detection over all the components by default. Also, the ChangeDetectorRef can be applied for detecting changes in the new references when the data gets mutated. The demand for angular development is keep on increasing which results in angular developer salary in India.

If you want to learn more about software technology, its development, and the mechanism behind it, you can check the course Executive PG Programme in Software Development – Specialisation in Full Stack Development offered by upGrad. The specialization course is a 23 weeks online program offering over 300+ case studies to boost up your knowledge and available tools and programming language to enhance your practical skills. If you have any more queries related to the course, drop us a message. Our team will contact you.

Frequently Asked Questions (FAQs)

1. What are the different change detection strategies in Angular?

Angular provides several change detection strategies to optimize the performance of change detection. However, the default strategy is named Detection. During this process, Angular walks the entire tree of components from the root to the children components. Each time the tree changes, Angular notifies the components by calling their _detectChanges method. For components that use the OnPush change detection strategy, Angular doesn’t walk the entire tree each time. Rather, it compares the current and previous values of data properties and calls the _detectChanges method only when a change occurs. By default, Angular uses the strategy that walks the entire tree.

2. What are directives in Angular?

Directives in Angular are reusable components. Directives allow extending HTML vocabulary and make it more dynamic. It is a new concept, which is being introduced in Angular, to extend the user interface. Directives are a special type of component, which can be used as an attribute, element or class. If a component is used as element, then it is called an element directive, if it is used as attribute, it is called an attribute directive and if it is used as classes, it is a class directive. There are around 11 built-in directives provided by Angular, like ng-repeat, ng-show, ng-controller etc. Angular also provides a facility to create custom directives.

3. What are the filters in Angularjs?

AngularJS provides several filters in addition to the filters provided by the browsers. Filters are strictly used in formatting the data before displaying it to the user. It is always recommended to filter the data using the filters so that the user gets to see the same data every time. Filters can also be used to make the data validation more efficient. Angular.js filters allow you to take a piece of HTML and manipulate it to your will, e.g. uppercase, lowercase, etc. Filters allow you to take an array of values and create a list of objects based on the values.

RELATED PROGRAMS