alegrowski
alegrowski

Reputation: 271

Injecting ElementRef to injecable error

I have an issue with injecting ElementRef to my Injectable. Here is my code:

import {Injectable, DynamicComponentLoader, ElementRef, Inject} from "angular2/core";
import {Modal} from './Modal';

@Injectable()
export class ModalService{
    constructor(public _dcl:DynamicComponentLoader, public _el:ElementRef){

    }

    createModal(parent){
        this._dcl.loadIntoLocation(Modal,this._el, 'modal')
    }


}

My Modal:

import {Component} from "angular2/core";

@Component({
    selector: 'modal',
    templateUrl: 'app/common/modal/Modal.html'
})

export class Modal{
    constructor(){

    }
}

This yields me to the following error:

No provider for ElementRef! (HomeComponent -> ModalService -> ElementRef)

Why?

Upvotes: 3

Views: 13157

Answers (2)

Matthieu Riegler
Matthieu Riegler

Reputation: 55971

You can inject ElementRef in a service if this service is provided by a component.

The component :

@Component({
    selector: 'app-rack-view',
    providers: [ MyService ],
})
export class MyComponent {}

The service:

@Injectable() 
export class MyService {
    constructor(private elementRef: ElementRef<HTMLDivElement>) {} // OK 
}

Upvotes: 6

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658235

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.

Upvotes: 10

Related Questions