Angular 2 runOutsideAngular still change the UI

前端 未结 5 1347
迷失自我
迷失自我 2020-12-01 11:12

From my understanding of runOutsideAngular(), if I need to run something that won\'t trigger the Angular change detection, I need to use this function. My code is not workin

5条回答
  •  鱼传尺愫
    2020-12-01 11:58

    Using ngZone.run is a bit better than the setTimeout solutions since it uses angular specific functionality. Run is meant to be used within ngZone.runOutsideAngular functions.

    From the docs:

    Running functions via run allows you to reenter Angular zone from a task that was executed outside of the Angular zone (typically started via {@link #runOutsideAngular}).

    This is actually a very practical example of say a button that increments a number by one but only triggers change detection when the number is even.

        @Component({selector: 'my-cmp', 
        template: `

    {{num}}

    `}) class MyComponent implements OnChanges { num = 1; constructor(private _ngZone: NgZone ) { } onClick() { this._ngZone.runOutsideAngular(() => { if(this.num % 2 === 0){ // modifying the state here wont trigger change. this.num++; } else{ this._ngZone.run(() => { this.num++; }) } }})); } }

提交回复
热议问题