获取根组件ElementRef或ComponentRef angular 2

时间:2016-01-24 00:30:15

标签: typescript angular

我在角度2中建立模态服务。我解决了大多数问题但是我有问题将模态组件以一种很好的角度方式放置在body元素中。我使用DynamicComponentLoader.loadNextToLocation函数来获取模态组件,并将其放在ElementRef函数中使用的DynamicComponentLoader.loadNextToLocation旁边。但是当我不想将创建的模态放在某个组件中时,我必须操纵DOM来插入创建的模态。我的问题是我可以在模态服务中使用我的应用程序中的根元素吗?我希望在特定元素不作为模态的容器提供时实现这一点。

var elementRef = DOM.query('app');
this.componentLoader.loadNextToLocation(ModalBackdrop, elementRef, backdropBindings)

5 个答案:

答案 0 :(得分:6)

要获取对根组件的引用,可以注入ApplicationRef

constructor(private app:ApplicationRef)
{
      let element: ElementRef = this._app['_rootComponents'][0].location;
}

答案 1 :(得分:5)

appElementRef: ElementRef;
constructor(private applicationRef:ApplicationRef, injector: Injector) {
  this.appElementRef = injector.get(applicationRef.componentTypes[0]).elementRef;
}

AppComponent需要提供返回elementRef的{​​{1}}字段。

另见https://github.com/angular/angular/issues/6446

答案 2 :(得分:1)

问题是要获取根ElementRef,应该引导您的应用程序。在某些情况下(在服务中获取ElementRef)我们应该等待。 我的解决方案:

import {Injectable, ApplicationRef, ElementRef} from 'angular2/core';

@Injectable()
export class SomeService {
  private _appElementRef: ElementRef;

  constructor(appRef: ApplicationRef) {
    appRef.registerBootstrapListener(appComponentRef => {
      this._appElementRef = appComponentRef.location;
    });
  }
}

答案 3 :(得分:1)

这适用于Angular 5.2.9

在根组件的构造函数中添加一个公共ElementRef:

export class AppComponent { 

constructor (public eltRef: ElementRef) { }

在要访问root的组件中,执行以下操作:

private rootRef: ElementRef;
constructor(private appRef: ApplicationRef) {
    this.rootRef = (this.appRef.components[0].instance as AppComponent).eltRef;
}

答案 4 :(得分:0)

可用的答案对我不起作用:

  • 所选答案要求根组件已注入 ElementRef
  • 投票最多的答案取决于访问私有变量,因此它可能会在没有警告的情况下中断(只有公共API更改才被视为中断更改并记录在案)
  • 其他答案假定根组件的类型为 AppComponent

在我的情况下,我正在开发一个第三方库,因此我无法做出任何假设,称其根名为 AppComponent 或已注入 ElementRef 。这就是对我有用的(Angular 6.1)

private readonly rootRef: ElementRef;

constructor(private appRef: ApplicationRef) {
  this.rootRef = appRef.components[0].injector.get(ElementRef);
}
相关问题