在Angular中手动触发变更检测 [英] Triggering change detection manually in Angular
本文介绍了在Angular中手动触发变更检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个具有属性Mode(): string
的Angular组件.
I'm writing an Angular component that has a property Mode(): string
.
我希望能够以编程方式设置此属性,而不响应任何事件.
I would like to be able to set this property programmatically not in response to any event.
问题在于,在没有浏览器事件的情况下,模板绑定{{Mode}}
不会更新.
The problem is that in the absence of a browser event, a template binding {{Mode}}
doesn't update.
是否可以手动触发此更改检测?
Is there a way to trigger this change detection manually?
推荐答案
尝试以下方法之一:
-
ApplicationRef.tick()
-与AngularJS的$rootScope.$digest()
类似-即,检查完整的组件树 -
NgZone.run(callback)
-与$rootScope.$apply(callback)
相似-即,在Angular区域内评估回调函数.我认为,但我不确定,这最终在执行回调函数后检查整个组件树. -
ChangeDetectorRef.detectChanges()
-与$scope.$digest()
相似-即,仅检查此组件及其子项
ApplicationRef.tick()
- similar to AngularJS's$rootScope.$digest()
-- i.e., check the full component treeNgZone.run(callback)
- similar to$rootScope.$apply(callback)
-- i.e., evaluate the callback function inside the Angular zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.ChangeDetectorRef.detectChanges()
- similar to$scope.$digest()
-- i.e., check only this component and its children
您可以将ApplicationRef
,NgZone
或ChangeDetectorRef
注入到组件中.
You can inject ApplicationRef
, NgZone
, or ChangeDetectorRef
into your component.
这篇关于在Angular中手动触发变更检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文