Pass an Injector to Embedded Views

Netanel Basal
Netanel Basal
Published in
1 min readJan 20, 2022

Angular v14.0.0 comes with a new feature, which allows an injector to be passed when using embedded views. In the past, it was only possible with the ngComponentOutlet directive or the createComponent API.

Let’s see how we can use it:

Directive Usage

When we pass a template to a component, the injector context for it and its child elements originates from the template declaration’s location, not from where it was created.

We can alter this behavior when needed and pass the component’s injector using this feature:

We’re creating a new provider in the component injector and passing the injector to the new ngTemplateOutletInjector directive. Now BarComponent will use the name declared in the FooComponent injector.

Note that the new injector acts as a node injector rather than a module injector.

ViewContainer Usage

The createEmbeddedView() method now accepts an injector as a third argument.

Follow me on Medium or Twitter to read more about Angular and JS!

--

--

Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.

Responses (4)