Search code examples
angulartypescriptangular2-changedetectionchange-detector-ref

What is the right way to use changeDetection.markForCheck() in Angular?


I am using markForCheck to detect changes in my angular component (Which has changeDetection: ChangeDetectionStrategy.OnPush) and initially, I put the markForCheck at the start of the function and It was working for me then I realized it will make more sense to put that after all the function action is done.

In both the approach angular was detecting the changes if it is called initially or after the action is done.

So if someone can justify what will be the right way to use markForCheck?

functionName() { // It works at both places
  this.cd.markForCheck();
  //
  .... Some Code that needs markForCheck ....
  //
  this.cd.markForCheck();
}

Solution

  • u need to use this.cdr.markForCheck() after changed some data and component have property changeDetection: ChangeDetectionStrategy.OnPush

    becouse in this case component will not reload self html template if some subchild components have OnPush - parent "markForCheck()" will redraw them too. if changed data display in subcomponent without OnPush u can don't use "markForCheck()"

    in my case compA have mat-table in html, so after reload items i call markForCheck() for redrawing mat-table