我有一个问题,把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')
}
}我的Modal
从“angular2/core”导入{Component};
@Component({
selector: 'modal',
templateUrl: 'app/common/modal/Modal.html'
})
export class Modal{
constructor(){
}
}这将导致以下错误:
没有ElementRef的提供者!(HomeComponent -> ModalService -> ElementRef)
为什么?
发布于 2016-04-08 09:12:01
不能将ElementRef注入服务类,只能注入组件或指令。ElementRef注入一个实例,其中.nativeElement指向附加组件或指令的DOM元素,但服务没有DOM元素。
在您的示例中,ElementRef不能是任何ElementRef。ElementRef确定将Modal组件添加到DOM的位置。
我建议您在DOM中添加一个单独的Modal组件,该组件提供以模式形式显示内容的服务。此组件注入一个全局共享服务并订阅事件。
其他想要使用Modal组件的组件也会注入全局服务,并发出一个组件类型,由订阅的Modal组件接收,然后使用DynamicComponentLoader将传递的组件添加到自己中,以显示为模态。
有关详细信息,请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
对此也有几个类似的问题。
发布于 2022-09-02 12:26:42
如果该服务由组件提供,则可以在服务中注入ElementRef。
构成部分:
@Component({
selector: 'app-rack-view',
providers: [ MyService ],
})
export class MyComponent {}服务:
@Injectable()
export class MyService {
constructor(private elementRef: ElementRef<HTMLDivElement>) {} // OK
}https://stackoverflow.com/questions/36495706
复制相似问题