I have an issue with injecting ElementRef
to my Injectable
. Here is my code:
import {Injectable, DynamicComponentLoader, ElementRef
You can't inject ElementRef
to a service class, only to a component or directive. ElementRef
injects an instance where .nativeElement
points to the DOM element the component or directive is attached to but there is no DOM element for a service.
In your example ElementRef
can't be any ElementRef
. The ElementRef
determines where you Modal
component is added to the DOM.
I suggest you add one single Modal
component somewhere to the DOM that provides the service of showing content as a modal. This component injects a globally shared service and subscribes to events.
Other components that want to use the Modal
component also inject the global service and emit a component type to be received by the subscribing Modal
component which then uses DynamicComponentLoader
to add the passed component to itself to be shown as modal.
For more details see https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
There are also several similar questions on SO already.