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?
ViewContainerRef
belongs to current component. A service is a singleton that can belong to current component's injector or parent injector. If it were instantiated by parent component and then injected into child component, it would have wrong view container reference. This doesn't make much sense. If you're already aware of a workaround, why asking this question? – Estabrookthis.modalService.viewContainerRef = this.viewContainerRef
workaround is a good choice for the same reason. Considering that service may be singleton, this definitely shouldn't be managed via DI. What exactly is your case? – Estabrook