Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inject ViewContainerRef into a service?

Tags:

angular

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.

like image 229
onetwothree Avatar asked Nov 16 '16 16:11

onetwothree


People also ask

What is the use of ViewContainerRef?

ViewContainerReflink. Represents a container where one or more views can be attached to a component.

Which method of ViewContainerRef create an instance of a component?

ViewContainerRef represents container where one or more view can be attached. This can contain two types of views. Host Views are created by instantiating a component using createComponent and Embedded Views are created by instantiating an Embedded Template using createEmbeddedView.

What is TemplateRef and ViewContainerRef in Angular?

A TemplateRef represents an <ng-template /> . <ng-template let-name let-date="dateNow">{{date}} - Hello {{name}}!</ng-template> An <ng-template /> itself will not do anything at all. We need a ViewContainerRef to insert the template somewhere.

What is Angular injector?

Injectors are data structures that store instructions detailing where and how services form. They act as intermediaries within the Angular DI system. Module, directive, and component classes contain metadata specific to injectors. A new injector instance accompanies every one of these classes.


1 Answers

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.

like image 151
Timothy Perez Avatar answered Nov 15 '22 09:11

Timothy Perez