Creating a Dynamic Component With a Custom Injector | Task

Ole Ersoy
Feb - 14  -  1 min

Scenario

Our HelloComponent takes a configuration constructor injected object.

When creating this component dynamically we wish to inject that component with the configuration value using Angular Dependency Injection, but without configuring the @ngModule.providers providers array or using providedIn:root.

Approach

Use the the imperative / programmatic way of performing constructor injection ReflectiveInjector to resolve and create the configuration for the component.

This is achieves the same end result as declaring the dependency in @ngModule.providers.

The reason we to do this to keep Angular from yelling at us about the object not being constructed properly, even if if the property is initialized post construction ( this.componentRef.instance.config = value;` ) — Yes Angular is also your mom:

const injector: Injector = ReflectiveInjector.resolveAndCreate(
[{
     provide: 'config', useValue: { 
     value: 'Any value or object here'}
}]);
const factory = cfr.resolveComponentFactory(HelloComponent);
const cr: ComponentRef<HelloComponent> = vc.createComponent(factory, 0, injector);
console.log(cr.instance.config);

Demo