Angular2 zone.run() vs ChangeDetectorRef.detectChanges()

和自甴很熟 提交于 2019-11-28 04:59:55
Günter Zöchbauer

ApplicationRef.tick (same as setTimeout()), and zone.run() cause change detection on the whole application. Also event listeners added within Angular or by Angular (using view bindings or @HostBinding() cause change detection for the whole application.

ChangeDetectorRef.detectChanges runs change detection for a specific component (and its descendants if applicable, for example because of input bindings)

If some code running outside Angular's zone calls into Angular's code and changes the state, then change detection needs to be invoked explicitly because Angular has no way of knowing that the state changed.

If the change to the state is local to a component (for example a components field), ChangeDetectorRef.detectChanges or ChangeDetectorRef.markforCheck are more efficient.

If the call from outside for example navigates to a different route, this can have consequences to a number of components, and it's also not clear when the whole route change is completed because it might cause async calls (and callbacks being called). In this case zone.run() is the better option, because the code directly and indirectly invoked (like callbacks of observables and promises) invoked will run inside Angular's zone and Angular will recognize them and invoke change detection automatically.

Babar Bilal

Both are totally different things.

NgZone is a lib that provide zones for your app so you can run the instances into multiple scopes.

ChangeDetection is always from parent to leaf like A > B > C When you call detectChanges() it will invoke the current component and its child components too. So this is the best approach to use OnPush changesdetectionStrategy for leaf components, so they will only detectChanges when inputs are updated.

Also, ApplicationRef is similar to ChangeDetector; the difference is it will detect changes from root component to last child component.

ChaneDetection and NgZone is best combination always to avoid the unnecessary ChangeDetection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!