Search code examples
angularangular2-changedetection

Can you use both OnChanges and DoCheck in an Angular 2 component?


I've got a scenario where I'd wish to use both ngOnChanges and ngDoCheck in my component, however I remember from some time ago in the angular docs that only one of these should be used at one time.

Although I can no longer seem to find this information, I think it said this somewhere in this section before.

Is it safe to use both of these or do I need to implement my own version of ngOnChanges in the DoCheck to avoid making a big "no no"?


Solution

  • The API doc for ngDoCheck says

    ngDoCheck gets called to check the changes in the directives in addition to the default algorithm.

    The Dev Guide LifeCycle Hooks doc says

    We also see that the ngOnChanges method is called in contradiction of the incorrect API documentation.

    But the API doc is correct now. It used to state that if you implemented ngDoCheck() then the default algorithm would not be called -- i.e., ngOnChanges() would not be called. (So, the Dev Guide is now incorrect for stating that the API docs are incorrect).

    It is perfectly fine to implement both.