How can I inject ViewContainerRef into a service?

后端 未结 2 890
走了就别回头了
走了就别回头了 2021-01-18 16:42

I\'m attempting to inject ViewContainerRef into a service, but am receiving error No provider for ViewContainerRef!. I found this PR, which address

相关标签:
2条回答
  • 2021-01-18 17:09

    Services are meant to be completely agnostic to any view. If you are trying to have a service associated with a particular view, then you should add it to the providers list within a specific parent component/directive and pass the ViewContainerRef as an argument into one of the service's methods.

    0 讨论(0)
  • 2021-01-18 17:18

    Make the service that you need the viewContainerRef in a singleton by adding it as a provider in app.module (and only app module); Inject that service into the component you need the containerRef of's constructor and have it call a setter method in the service that sets its containerRef to a variable in the service for future use.

    The component you want to pass its ref

    export class PrintPortalComponent {
    
      constructor(
        private printPortalService: PrintPortalService, 
        public viewContainerRef: ViewContainerRef
      ) {
        this.printPortalService.printPortalRef = this.viewContainerRef;
      }
    
    }
    

    Your singleton service

    export class PrintPortalService {
    
      public viewContainerRef: ViewContainerRef;
    
      set printPortalRef(vcr: ViewContainerRef) {
        this.viewContainerRef = vcr;
      }
    }
    

    I struggled with this for hours until i found this: How do I create a singleton service in Angular 2?

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