Angular2 - How Digest cycle works in angular2/4

13,817

Solution 1

In Angular, the concept of change detection is automatic. There is no $scope , hence In $scope.$watch() and $scope.$digest() are no more.

You can read more on Change Detection.

Solution 2

In AngularJS most components/directives have a $scope associated with them. Each $scope has a set of watch functions attached to it. These watch functions perform certain tasks but the most import task is probably DOM update added through interpolation {{...}} syntax or by ng-bind directive. So imagine you have 3 components/directives that form a hierarchy of $scopes:

AComponentScope
    BComponentScope
       CComponentScope

So when AngularJS runs $digest it first triggers the watcher that updates DOM for AComponentScope, then for BComponentScope and then for CComponentScope.

In Angular there's also a task to update the DOM as part of change detection/digest. This task is performed by updateRenderer function that is generated for each component based on the template. So when Angular runs change detection it triggers that function for each component recursively just as in AngularJS. The only difference is that this process happens only once from top down while in AngularJS this process can happen up to 10 times.

For more information read these articles:

Solution 3

Try this if you are also having issue with Angular default change detection mechanism. In my case, in my ionic4 Project default change mechanism of Angular was somewhat not working properly so I triggered it manually.

constructor(private ref: ChangeDetectorRef) {
     ref.detach();
     setInterval(() => {
         this.ref.detectChanges();
     }, 500);
 }
Share:
13,817

Related videos on Youtube

georgeawg
Author by

georgeawg

Updated on June 04, 2022

Comments