Angular2 - How Digest cycle works in angular2/4
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:
- Angular’s $digest is reborn in the newer version of Angular
- Everything you need to know about change detection in Angular
- The mechanics of DOM updates in Angular
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);
}
Related videos on Youtube
georgeawg
Updated on June 04, 2022Comments
-
georgeawg almost 2 years
How diagest cycle mechanisam achieved in Angular2, Ex : $scope is single object which keep on watching its child elements and trigger for change How angular2 done this with out $scope
-
Günter Zöchbauer over 6 years
-
Günter Zöchbauer over 6 years
-
Max Koretskyi over 6 years
-
Max Koretskyi over 6 yearsis there anything unclear about my answer?
-