问题描述
根据我对,如果我需要运行一些不会触发Angular变化检测的东西,我需要使用这个函数。但是,我的代码不起作用;当我点击按钮时,UI正在改变,数字是2。
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 working, however; 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;
}}));
}
}
推荐答案
如果任何事情都会导致更改检测,并且绑定事件(如(click)=onClick()
确实会导致更改检测,然后Angular将检测到更改。
If anything is causing change detection, and a bound event like (click)="onClick()"
does cause change detection, then Angular will detect the change.
runOutsideAngular
并不意味着Angular不会看到变化,它只意味着代码以这种方式运行不会导致更改检测,但因为click事件已经发生,所以在您的示例中它没有意义。
runOutsideAngular
doesn't mean Angular won't see the change, it 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.
这篇关于Angular 2 runOutsideAngular仍然会更改UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!