Injecting ElementRef to injecable error

前端 未结 1 1827
既然无缘
既然无缘 2020-12-21 17:47

I have an issue with injecting ElementRef to my Injectable. Here is my code:

import {Injectable, DynamicComponentLoader, ElementRef         


        
相关标签:
1条回答
  • 2020-12-21 18:19

    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.

    0 讨论(0)
提交回复
热议问题