本文介绍了如何在 Angular 2 中强制重新渲染组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Angular 2 中强制重新渲染组件?为了使用 Redux 进行调试,我想强制一个组件重新渲染它的视图,这可能吗?

How to force a component's re-rendering in Angular 2?For debug purposes working with Redux i'd like to force a component to re-render it's view, is that possible?

推荐答案

渲染发生在更改检测之后.要强制更改检测,以便将更改的组件属性值传播到 DOM(然后浏览器将在视图中呈现这些更改),这里有一些选项:

Rendering happens after change detection. To force change detection, so that component property values that have changed get propagated to the DOM (and then the browser will render those changes in the view), here are some options:

  • ApplicationRef.tick() - 类似于 Angular 1 的 $rootScope.$digest() -- 即检查完整的组件树
  • NgZone.run(callback) - 类似于 $rootScope.$apply(callback) -- 即,评估 Angular 2 区域内的回调函数.我想,但我不确定,这最终会在执行回调函数后检查完整的组件树.
  • ChangeDetectorRef.detectChanges() - 类似于 $scope.$digest() -- 即,只检查这个组件及其子组件
  • ApplicationRef.tick() - similar to Angular 1'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 2 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 will need to import and then inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

对于您的特定场景,如果只有一个组件发生了变化,我会推荐最后一个选项.

For your particular scenario, I would recommend the last option if only a single component has changed.

这篇关于如何在 Angular 2 中强制重新渲染组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 14:53