Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

angular - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...