Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting ElementRef to injecable error

Tags:

angular

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?

like image 925
alegrowski Avatar asked Mar 19 '26 16:03

alegrowski


1 Answers

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.

like image 134
Günter Zöchbauer Avatar answered Mar 22 '26 04:03

Günter Zöchbauer