Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get root component ElementRef or ComponentRef angular 2

I'm building modal service in angular 2. I resolve most of the issues but i have problem placing the modal component in the body element in a nice angular way. I use DynamicComponentLoader.loadNextToLocation function to get the modal component and place it next to the ElementRef that is uset in DynamicComponentLoader.loadNextToLocation function. But when i don't want to place the created modal inside some component i have to manipulate DOM to insert the created modal. My question is can i use the root element in my application in the modal service? I want to achieve this when specific element isn't provided as container for the modal.

var elementRef = DOM.query('app');
this.componentLoader.loadNextToLocation(ModalBackdrop, elementRef, backdropBindings)
like image 451
Kliment Avatar asked Jan 24 '16 00:01

Kliment


People also ask

What are the difference between renderer and ElementRef in Angular 2?

The Renderer is a class that is a partial abstraction over the DOM. Using the Renderer for manipulating the DOM doesn't break server-side rendering or Web Workers (where direct access to the DOM would break). ElementRef is a class that can hold a reference to a DOM element.

How do I get ElementRef from components?

So if you want to get ElementRef from the child that is angular2 component ( VerticeControlComponent ) you need to explicitely tell using read: ElementRef : @ViewChild('scaleControl', {read: ElementRef}) scaleControl: ElementRef; And then inside ngAfterViewInit hook or later you can write this.

What is the use of ElementRef in Angular?

Angular ElementRef is a wrapper around a native element inside of a View. It's simply a class that wraps native DOM elements in the browser and allows you to work with the DOM by providing the nativeElement object which exposes all the methods and properties of the native elements.

How do I get ElementRef in Angular 8?

Getting ElementRef in Component ClassCreate a template reference variable for the element in the component/directive. Use the template variable to inject the element into component class using the ViewChild or ViewChildren.


2 Answers

To get a reference to the root component, you can inject ApplicationRef:

constructor(private app:ApplicationRef)
{
      let element: ElementRef = this.app['_rootComponents'][0].location;
}
like image 162
pixelbits Avatar answered Nov 15 '22 10:11

pixelbits


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

The AppComponent would need to provide the elementRef field that returns the ElementRef though.

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

like image 24
Günter Zöchbauer Avatar answered Nov 15 '22 09:11

Günter Zöchbauer