Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 将ElementRef注入不可纠正错误_Angular - Fatal编程技术网

Angular 将ElementRef注入不可纠正错误

Angular 将ElementRef注入不可纠正错误,angular,Angular,我在将ElementRef注入到我的Injectable时遇到问题。这是我的密码: import {Injectable, DynamicComponentLoader, ElementRef, Inject} from "angular2/core"; import {Modal} from './Modal'; @Injectable() export class ModalService{ constructor(public _dcl:DynamicComponentLoade

我在将
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')
    }


}
我的<代码>模式<代码>:

从“angular2/core”导入{Component}

这使我产生以下错误:

ElementRef没有提供程序!(HomeComponent->ModalService->ElementRef)


为什么?

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

在您的示例中,
ElementRef
不能是任何
ElementRef
ElementRef
确定将
Modal
组件添加到DOM的位置

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

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

有关更多详细信息,请参阅


已经有几个类似的问题了。

嗯,这很有趣。渲染器也是这样吗?不,
renderer
没有与特定组件链接,而是针对
renderer
上的每个方法调用,您需要传递
elementRef.nativeElement
。您想在DOM中的何处添加
模式
ElementRef
需要指向连接到DOM的现有组件。
@Component({
    selector: 'modal',
    templateUrl: 'app/common/modal/Modal.html'
})

export class Modal{
    constructor(){

    }
}