【发布时间】:2017-06-16 07:31:21
【问题描述】:
我不明白ApplicationRef 类及其用途。有一个“reference to an Angular application running on a page”是什么意思?什么时候需要?
请提供一个使用ApplicationRef的小例子。
【问题讨论】:
标签: angular
我不明白ApplicationRef 类及其用途。有一个“reference to an Angular application running on a page”是什么意思?什么时候需要?
请提供一个使用ApplicationRef的小例子。
【问题讨论】:
标签: angular
https://angular.io/api/core/ApplicationRef
appRef.tick() 来调用应用程序范围的更改检测
attachView() 和detachView() 添加/删除要包含在更改检测中或从更改检测中排除的视图
componentTypes 和components 提供已注册组件和组件类型的列表
以及其他一些变更检测相关信息【讨论】:
ApplicationRef 包含对根视图的引用,可用于使用tick 函数手动运行更改检测
调用此方法以显式处理更改检测及其 副作用。
在开发模式下,tick() 还会执行第二次更改检测 循环以确保没有检测到进一步的变化。如果额外 在第二个周期中获取更改,应用程序中的绑定 具有无法在单个更改检测中解决的副作用 经过。在这种情况下,Angular 会抛出一个错误,因为 Angular 应用程序只能有一个更改检测通过,在此期间所有 必须完成变更检测。
这是一个例子:
@Component()
class C {
property = 3;
constructor(app: ApplicationRef, zone: NgZone) {
// this emulates any third party code that runs outside Angular zone
zone.runOutsideAngular(()=>{
setTimeout(()=>{
// this won't be reflected in the component view
this.property = 5;
// but if you run detection manually you will see the changes
app.tick();
})
})
如果它是使用根节点创建的,另一个应用程序是附加一个动态创建的组件视图以进行更改检测:
addDynamicComponent() {
let factory = this.resolver.resolveComponentFactory(SimpleComponent);
let newNode = document.createElement('div');
newNode.id = 'placeholder';
document.getElementById('container').appendChild(newNode);
const ref = factory.create(this.injector, [], newNode);
this.app.attachView(ref.hostView);
}
查看this answer了解更多详情。
【讨论】: