Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

angular - Why do we need `ngDoCheck`

I can't seem to figure out why I need ngDoCheck lifecycle hook other than for simple notification, particularly how writing code inside of it makes a difference as regard to change detection. Most of the examples I've found show useless examples, like this one, with a bunch of logging functionality.

Also, in the generated classes I don't see it being used for something else other than simple notification:

conmponent/wrapper.ngfactory.js

Wrapper_AppComponent.prototype.ngDoCheck = function(view,el,throwOnChange) {
  var self = this;
  var changed = self._changed;
  self._changed = false;
  if (!throwOnChange) {
    if (changed) {
      jit_setBindingDebugInfoForChanges1(view.renderer,el,self._changes);
      self._changes = {};
    }
    self.context.ngDoCheck(); <----------- this calls ngDoCheck on the component
                                               but the result is not used 
                                               anywhere and no params are passed
  }
  return changed;
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This great article If you think ngDoCheck means your component is being checked?—?read this article explains the error in depth.

The contents of this answer is based on the angular version 2.x.x. For the most recent version 4.x.x see this post.

There is nothing on the internet on the inner workings of change detection, so I had to spend about a week debugging sources, so this answer will be pretty technical on details.

An angular application is a tree of views (AppView class that is extended by the Component specific class generated by the compiler). Each view has a change detection mode that lives in cdMode property. The default value for cdMode is ChangeDetectorStatus.CheckAlways, which is cdMode = 2.

When a change detection cycle runs, each parent view checks whether it should perform change detection on the child view here:

      detectChanges(throwOnChange: boolean): void {
        const s = _scope_check(this.clazz);
        if (this.cdMode === ChangeDetectorStatus.Checked ||
            this.cdMode === ChangeDetectorStatus.Errored)
          return;
        if (this.cdMode === ChangeDetectorStatus.Destroyed) {
          this.throwDestroyedError('detectChanges');
        }
        this.detectChangesInternal(throwOnChange); <---- performs CD on child view

where this points to the child view. So if cdMode is ChangeDetectorStatus.Checked=1, the change detection is skipped for the immediate child and all its descendants because of this line.

    if (this.cdMode === ChangeDetectorStatus.Checked ||
            this.cdMode === ChangeDetectorStatus.Errored)
          return;

What changeDetection: ChangeDetectionStrategy.OnPush does is simply sets cdMode to ChangeDetectorStatus.CheckOnce = 0, so after the first run of change detection the child view will have its cdMode set to ChangeDetectorStatus.Checked = 1 because of this code:

    if (this.cdMode === ChangeDetectorStatus.CheckOnce) 
         this.cdMode = ChangeDetectorStatus.Checked;

Which means that the next time a change detection cycle starts there will be no change detection performed for the child view.

There are few options how to run change detection for such view. First is to change child view's cdMode to ChangeDetectorStatus.CheckOnce, which can be done using this._changeRef.markForCheck() in ngDoCheck lifecycle hook:

      constructor(private _changeRef: ChangeDetectorRef) {   }
    
      ngDoCheck() {
        this._changeRef.markForCheck();
      }

This simply changes cdMode of the current view and its parents to ChangeDetectorStatus.CheckOnce, so next time the change detection is performed the current view is checked.

Check a full example here in the sources, but here is the gist of it:

          constructor(ref: ChangeDetectorRef) {
            setInterval(() => {
              this.numberOfTicks ++
              // the following is required, otherwise the view will not be updated
              this.ref.markForCheck();
              ^^^^^^^^^^^^^^^^^^^^^^^^
            }, 1000);
          }

The second option is call detectChanges on the view itself which will run change detection on the current view if cdMode is not ChangeDetectorStatus.Checked or ChangeDetectorStatus.Errored. Since with onPush angular sets cdMode to ChangeDetectorStatus.CheckOnce, angular will run the change detection.

So ngDoCheck doesn't override the changed detection, it's simply called on every changed detection cycle and it's only job is to set current view cdMode as checkOnce, so that during next change detection cycle it's checked for the changes. See this answer for details. If the current view's change detection mode is checkAlways (set by default if onPush strategy is not used), ngDoCheck seem to be of no use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...