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

1.5k Views Asked by At

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();
}
2

There are 2 best solutions below

0
On BEST ANSWER

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

3
On

You use markForCheck() to tell Angular to 'flag' changes that happened outside of the active change detection strategy.

When you are using the default change detection strategy, markForCheck() is not necessary and my guess is that is why it didn't matter where you originally had your markForCheck() call.

The correct place to call markForCheck() is inside a component with ChangeDetectionStrategy.OnPush after you make changes that won't get picked up by the OnPush change detection.

Here is a more in-depth explanation that you might find helpful, What's the difference between markForCheck() and detectChanges()

EDIT: I mistakenly said that markForCheck() triggers the change detection and that is incorrect. Thanks @Fatih Ersoy