Search code examples
angularangular6angular2-changedetectionangular7

Workings of the function checkAndUpdateDirectiveInline in changeDetection


I am trying to understand changeDetection in Angular and am not able to get past the function checkAndUpdateDirectiveInline in provider.ts. Source code here . Would really appreciate if you could expound on the reason for the multiple 'if' conditions used in the function and how the function determines when and which lifecycle hook to call. For example the following excerpt from the function does not speak much to me :

if (def.flags & NodeFlags.DoCheck) {
    directive.ngDoCheck();
  }

Solution

  • Would really appreciate if you could expound on the reason for the multiple 'if' conditions used in the function

    Multiple if conditions is just an in-lined version of the checkAndUpdateDirectiveDynamic function below. It used to be a faster implementation, not sure now.

    how the function determines when and which lifecycle hook to call.

    def.flags is a bitmask, it has certain bits set for hooks:

    export const enum NodeFlags {
      ...
      OnInit = 1 << 16,
      OnDestroy = 1 << 17,
      DoCheck = 1 << 18,
      OnChanges = 1 << 19,
      AfterContentInit = 1 << 20,
      AfterContentChecked = 1 << 21,
      AfterViewInit = 1 << 22,
      AfterViewChecked = 1 << 23,
    

    it's set by compiler which checks if method is implemented on a component class during compilation. The statement def.flags & NodeFlags.DoCheck simply checks if bit is set.