对于组件MyDemoComponent
@Component({
selector : 'my-demo-component',
template : '<div> Demo </div>'
})
class MyDemoComponent { };
MyDemoModule
@NgModule({
imports : [SomeOtherModule],
declarations: [AnotherComponent, SomeOtherComponent],
export : [MyDemoComponent]
})
class MyDemoModule { }
现在有任何方法可以获得MyDemoModule
向MyDemoComponent
提供的所有组件,服务和管道的列表。
从what I have looked到目前为止,我可以使用ViewContainerRef.parentInjector
这是我正在寻找的服务集合(排序)。但是,我仍然不知道如何获取MyDemoComponent
中使用的指令和管道列表。
我基本上是在尝试创建一个可以动态创建其他组件的组件,类似于this question。但是,在动态创建的组件的视图中,我想使用在父模块中注册的组件,服务和管道。
编辑:我在这里发布代码的相关部分,我提到的列表将帮助我:
export class DynamicComponentCreator {
@Input() html: string;
constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {}
ngOnChanges() {
const html = this.html;
if (!html) return;
@Component({
selector: 'dynamic-comp',
template: html
})
class DynamicHtmlComponent { };
@NgModule({
imports: [CommonModule],
declarations: [DynamicHtmlComponent]
})
class DynamicHtmlModule {}
this.compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
.then(factory => {
const compFactory = factory.componentFactories
.find(x => x.componentType === DynamicHtmlComponent);
const cmpRef = this.vcRef.createComponent(compFactory, 0);
});
}
}
正如您所看到的,我在内部创建的模块无法配置为使用父模块可用的服务/组件/管道。此代码稍微修改了this question
中的内容答案 0 :(得分:1)
获取Injector
引用很简单:
constructor(private injector:Injector)
{
}
您不需要自己获取组件列表,如果您的模块配置正确,一切都会自动解决。
请参阅ComponentFactoryResolver
,ComponentFactory
文档。
默认情况下,您无法从组件访问模块实例,但您可以自己提供模块:
{
provide : 'module', //better use OpaqueToken
useExisting: forwardRef(() => AppModule),
}
现在可以将模块注入组件:@Inject('module') module:any
然后使用Reflect元数据包提取模块参数。