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)
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.
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.
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.
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.
To get a reference to the root component, you can inject ApplicationRef:
constructor(private app:ApplicationRef)
{
let element: ElementRef = this.app['_rootComponents'][0].location;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With