将ElementRef注入到可注射的错误中

ale*_*ski 2 angular

我有注射ElementRef到我的问题Injectable.这是我的代码:

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')
    }


}
Run Code Online (Sandbox Code Playgroud)

我的Modal:

从"angular2/core"导入{Component};

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

export class Modal{
    constructor(){

    }
}
Run Code Online (Sandbox Code Playgroud)

这让我产生以下错误:

没有ElementRef的提供者!(HomeComponent - > ModalService - > ElementRef)

为什么?

Gün*_*uer 9

您不能注入ElementRef服务类,只能注入组件或指令.ElementRef注入一个实例,其中.nativeElement指向组件或指令所附加的DOM元素,但是服务没有DOM元素.

在你的例子ElementRef中不能是任何 ElementRef.在ElementRef决定了您Modal组件添加到DOM.

我建议你Modal在DOM的某处添加一个单独的组件,提供将内容显示为模态的服务.此组件注入全局共享服务并订阅事件.

想要使用该Modal组件的其他组件也注入全局服务并发出要由订阅组件接收的组件类型Modal,然后该订阅组件DynamicComponentLoader将传递的组件添加到其自身以显示为模态.

有关详细信息,请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

关于SO还有几个类似的问题.


Mat*_*ler 6

ElementRef如果某个服务是由组件提供的,那么您可以注入该服务。

组件:

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

服务:

@Injectable() 
export class MyService {
    constructor(private elementRef: ElementRef<HTMLDivElement>) {} // OK 
}
Run Code Online (Sandbox Code Playgroud)