Angular更新检测是自动执行的,但是有些情况下我们需要手动触发更新检测,Angular提供以下方法来手动触发更新检测:
- detectChanges(): Forces an immediate check for the component and its children.
- markForCheck(): Marks the component to be checked in the next cycle (useful with OnPush).
- detach()/reattach(): Temporarily disables or re-enables change detection for a component.
When to use detectChanges
The follow cases are when you should use detectChanges
:
1. When change detector is detached
from current component.
1 | ngDoCheck(): void { |
2. An update is happened, but its not in Angular zone, for example: 3rd party libraries.
1 | myFunction(){ |
Note that we can also fix this by wrapping the third party code in setTimeout
or NgZone.run
:
1 | myFunction(){ |
1 | myFunction(){ |
Angular has monkey patched setTimeout
, and will do the change detection after the setTimeout
is finished.
3. There are also cases where you update the model after the change detection cycle is finished, where in those cases you get this dreaded error: "Expression has changed after it was checked";
When to use markForCheck
The most common case to use markForCheck
is when your component use OnPush
change detection strategy and you want to trigger change detection for the component and its ancestors.
1 | import {ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit} from '@angular/core'; |
Difference between detectChanges
and markForCheck
detectChanges
triggers change detection for thecomponent and its children
.markForCheck
marks thecomponent and its ancestors
for change detection, but it doesn’t trigger change detection immediately.detectChanges
still work even when change detector isdetached
, butmarkForCheck
doesn’t.