在Angular 2+中ApplicationRef的目的是什么?

Bha*_*han 5 angular

我不明白这个ApplicationRef课程及其用途.拥有" 对页面上运行的Angular应用程序的引用 "是什么意思?什么时候需要?

请提供一个小例子ApplicationRef.

Gün*_*uer 15

https://angular.io/api/core/ApplicationRef

  • 允许通过调用来调用应用程序范围的更改检测 appRef.tick()
  • 它允许添加/删除视图将被包括在或者使用来自变化检测中排除attachView()detachView()
  • 提供了使用登记的部件和部件类型的列表componentTypescomponents 一些其他变化检测相关的信息


Max*_*kyi 12

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();
          })
       })
Run Code Online (Sandbox Code Playgroud)

另一个应用程序是附加动态创建的组件视图以进行更改检测(如果它是使用根节点创建的):

  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);
  }
Run Code Online (Sandbox Code Playgroud)

查看此答案以获取更多详细信息

  • 我建议添加一些关于注册组件 API 的详细信息,这绝对是最好的答案:) (2认同)