Why NG Change Instead Of Watch In Angular JS
Posted By : Milind Ahuja | 29-Mar-2018
In the olden days, when there were no MVC supportive frameworks like Angular and co., you were used to doing the following stuff in jQuery:
function showNameChanged() {
// stuff...
}
$('input.show-name').change(showNameChanged);
This simply performs an operation whenever any change occurs inside an input.
In Angular though, most of us would go with the following approach :
$scope.$watch('show.name', showNameChanged);
I would have written this like this also:
Why ng-change?.
Most of the Angular users seem to reach $watch first, instead of ng-change. ng-change is simply a directive that operates just like a change event listener in jQuery.
What are the differences?
-
In case of ng-change, it would call our function showNameChanged() only if there are any actual changes in the input. Whereas, Watches are called in many other cases as well, like at the time of defining them the first time and on every digest loop. This could potentially cause the $digest limit to be reached or affect the performance.
-
Another plus point for ng-change is that you can see from the template who this input is bound to something, otherwise you would need to look for the value in ng-model. With ng-change, the change will be triggered by a user action on a particular input element.
-
Using ng-change is a bit more performant as it uses one less watch expression. Angular doesn't need to keep evaluating it on every digest cycle, which is the case if you $watch.
Final Words
Usually, if your Angular App is slow, it is mostly due to the use of too many watchers. Angular performs dirty checking to track all the changes in an app, which means it will go through every watcher to check if there is anything to update.
So reducing the number of watches will not only affect the memory's footprint reduction but also it reduces the amount of time taken in each digest cycle.
THANKS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Milind Ahuja
Milind is a bright Lead Frontend Developer and have knowledge of HTML, CSS, JavaScript, AngularJS, Angular 2+ Versions and photoshop. His hobbies are learning new computer techniques, fitness and interest in different languages.