[英]How to inject providers for dynamic components in Angular?
I'm trying to inject providers for my dynamic components. 我正在尝试为我的动态组件注入提供程序。 But I'm getting StaticInjectionError.
但是我收到了StaticInjectionError。 But not sure, how to fix this issue.
但不确定如何解决此问题。 I have provided the Stackblitz example below.
我在下面提供了Stackblitz示例。
https://stackblitz.com/edit/angular-cr1vkv https://stackblitz.com/edit/angular-cr1vkv
createComponent() {
// THIS IS NOT WORKING
let injector = Injector.create([{
provide: 'TEST', useValue: 'Manoj'
}]);
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(HelloComponent);
componentFactory.create(injector);
let viewContainerRef = this.adHost.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
}
I looked at your StackBlitz, and looks like you need to pass your custom injector
to ViewContainerRef#createComponent
method as its 3rd parameter. 我查看了您的StackBlitz,看来您需要将自定义
injector
作为其第3个参数传递给ViewContainerRef#createComponent
方法。
let componentRef = viewContainerRef.createComponent(componentFactory, 0, injector);
Also, you need to get rid of: 另外,您需要摆脱:
componentFactory.create(injector);
That solves your issue. 那解决了您的问题。
Here is screen grab of working code. 这是工作代码的屏幕截图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.