I'm having major trouble trying to perform some logic inside a (click)
event callback function in Angular 2 without triggering change detection.
Why I don't want to trigger change detection
The callback function performs a simple animated scroll to top. It effects no other components and therefore I don't need change detection to fire in every component, in fact I really don't want it to fire! Because change detection does fire in every component, the performance of the animation on mobile is extremely poor.
What I've tried
I know I can run code outside of the zone using
this._zone.runOutsideAngular(() => {
someFunction();
})
This works nicely when the code you want to run outside the zone isn't invoked by a click
, keyup
, keydown
event etc.
Because my component looks like...
<button (click)="doThing()">Do that thing outside the zone!</button>
doThing() {
this._zone.runOutsideAngular(() => {
myFunction();
})
}
...myFunction
will be run outside the zone but the click
event will trigger change detection.
I've already implemented OnPush
change detection strategy in as many of my components as possible.
It's important that change detection is not triggered here but I can't find a way to prevent it.
Edit
See this plnk with change detection set to OnPush
in all components. Clicking the subrow component button triggers CD in the subrow, row and app components.
changeDetection: ChangeDetectionStrategy.OnPush
in that component's@Component({})
decorator??? – Mimeograph