onetwothree
onetwothree

Reputation: 682

How can I inject ViewContainerRef into a service?

I'm attempting to inject ViewContainerRef into a service, but am receiving error No provider for ViewContainerRef!. I found this PR, which addresses exactly what I'm after and it appears to have been merged.

Note that I am aware of how to achieve this by using a placeholder using this.

Upvotes: 7

Views: 16140

Answers (2)

steve kedzior
steve kedzior

Reputation: 141

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?

Upvotes: 6

Grey Perez
Grey Perez

Reputation: 20468

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.

Upvotes: 8

Related Questions