user2999287 user2999287 - 1 month ago 22
Javascript Question

Angular 2 runOutsideAngular still change the UI

I am trying to understand the runOutsideAngular, and from my understanding, if I need to run something that not trigger the Angular change detection I need to use this function. but my code does not working, when I click the button the UI is changing and the number is 2.

@Component({selector: 'my-cmp',
template: `<h1>{{num}}</h1>
<button (click)="onClick()">Change number</button>`})

class MyComponent implements OnChanges {

num = 1;
constructor(private _ngZone: NgZone ) {

}

onClick() {
this._ngZone.runOutsideAngular(() => {
this.num = 2;
}}));
}
}

Answer

If anything is causing change detection, and a bound event like (click)="onClick()" does cause change detection, then Angular will detect the change.

rounOutsideAngular doesn't mean Angular won't see the change, only only means that the code run this way doesn't cause change detection, but because the click event already does, it's meaningless in your example.