简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM