Get root component ElementRef or ComponentRef angular 2

I create a modal service in angular 2. I solve most of the problems, but I have a problem with placing the modal component in the body element in a good angular way. I use a function DynamicComponentLoader.loadNextToLocationto get a modal component and place it next to ElementRefwhich is used in the function DynamicComponentLoader.loadNextToLocation. But when I do not want to put the created modal inside some component, I have to manipulate the DOM to insert the created modal. My question is: can I use the root element in my application in a modal service? I want to achieve this when a specific item is not provided as a container for modal.

var elementRef = DOM.query('app');
this.componentLoader.loadNextToLocation(ModalBackdrop, elementRef, backdropBindings)
+5
source share
5 answers
appElementRef: ElementRef;
constructor(private applicationRef:ApplicationRef, injector: Injector) {
  this.appElementRef = injector.get(applicationRef.componentTypes[0]).elementRef;
}

AppComponentyou must specify the field elementRefthat returns elementRef.

See also https://github.com/angular/angular/issues/6446

+6
source

To get a link to the root component, you can add ApplicationRef :

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

, 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;
    });
  }
}
+1

Angular 5.2.9

ElementRef :

export class AppComponent { 

constructor (public eltRef: ElementRef) { }

, , :

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

:

  • , ElementRef.
  • , ( API )
  • , AppComponent.

, , AppComponent ElementRef. (Angular 6.1)

private readonly rootRef: ElementRef;

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

Later, I discovered that if I tried to deploy and use the service very early after Angular bootstrap, an exception occurred because it appRef.componentswas still empty. So instead, I changed the code to make a rootRefpromise that resolves with ElementRef. Thus, the consumer code can call it immediately without causing an exception, but it will have to wait for permission ElementRef:

private readonly rootRef: Promise<ElementRef>;

constructor(appRef: ApplicationRef) {
  this.rootRef = new Promise(resolve => {
    setTimeout(
      () => resolve(appRef.components[0].injector.get(ElementRef)),
      100
    );
  });
}
+1
source

Source: https://habr.com/ru/post/1625679/


All Articles