I\'m attempting to inject ViewContainerRef
into a service, but am receiving error No provider for ViewContainerRef!
. I found this PR, which address
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.
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?