在Angular中手动触发变更检测 [英] Triggering change detection manually in Angular

查看:641
本文介绍了在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() - 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中手动触发变更检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆