本文介绍了在 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 tree
  • NgZone.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

您可以将 ApplicationRefNgZoneChangeDetectorRef 注入到您的组件中.

You can inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

这篇关于在 Angular 中手动触发变更检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:26