简体   繁体   English

如何对动态 Angular 组件进行依赖注入

[英]How to do dependency injection for Dynamic Angular Components

I am trying to build a dynamic component inside any container.我正在尝试在任何容器内构建一个动态组件。 I needed some predefined services and injections available in the angular world inside the dynamically created component.我需要在动态创建的组件内的 angular 世界中提供一些预定义的服务和注入。 Primary reason for this there is an external service that holds the responsibility of look of the component but Additional actions needs be performed on component in the client side.造成这种情况的主要原因是有一个外部服务负责组件的外观,但需要在客户端的组件上执行其他操作。

private elementRef: ElementRef in the constructor of dynamic component for injection causes problem and it unable to provide values for injection. private elementRef:用于注入的动态组件的构造函数中的ElementRef导致问题,它无法为注入提供值。 Getting the error - "ERROR Error: Can't resolve all parameters for Xyz: (?)."收到错误 - “错误错误:无法解析 Xyz 的所有参数:(?)。”

const component = Component({
            template: div,
            selector: 'test'
        })(
            class Xyz {
                constructor(private elementRef: ElementRef) { }
            });
        const module = NgModule({ declarations: [component] })(class {
        });
        this.compiler.compileModuleAndAllComponentsAsync(module)
            .then((factories) => {
                const f = factories.componentFactories[0];
                const cmpRef = f.create(this.injector, [], null, this.ngModuleRef);
                                container.clear();
                container.insert(cmpRef.hostView);
             });

What is the best way to inject or pass parameters to a constructor that is dynamically created?将参数注入或传递给动态创建的构造函数的最佳方法是什么?

It works if you define Component and NgModule as @Component and @NgModule syntax.如果将 Component 和 NgModule 定义为 @Component 和 @NgModule 语法,它就可以工作。 I had the same problem when using the approach you used.使用您使用的方法时,我遇到了同样的问题。 I don't know the exact reason why one doesn't work and the other does.我不知道为什么一个不起作用而另一个起作用的确切原因。 Check this accepted answer: How to access the function when using dynamic injecting component in Angular检查这个接受的答案: How to access the function when using dynamic injection component in Angular

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM