Reputation: 2584
For a component MyDemoComponent
@Component({
selector : 'my-demo-component',
template : '<div> Demo </div>'
})
class MyDemoComponent { };
Which has been included in MyDemoModule
@NgModule({
imports : [SomeOtherModule],
declarations: [AnotherComponent, SomeOtherComponent],
export : [MyDemoComponent]
})
class MyDemoModule { }
Now is there any way I can get a list of all the components , services and pipes that MyDemoModule
makes available to MyDemoComponent
.
From what I have looked up so far I can use ViewContainerRef.parentInjector
which is a (sort) of collection of services I was looking for. However I am still at a loss as to how to get the list of directives and pipes that are used in MyDemoComponent
.
I am basically trying to create a component that can dynamically create other components, similar to this question. However In the views of the dynamically created components I want to use the components,services and pipes registered in the parent module.
EDIT : Here I am posting the relevant section of code where the list I mentioned will help me :
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);
});
}
}
As you can see the module I'm creating inside cannot be configured to use the services/components/pipes available to parent module. This code is slightly modified from what is seen in this question
Upvotes: 2
Views: 1469
Reputation: 15270
Obtaining Injector
reference is simple:
constructor(private injector:Injector)
{
}
You dont need to get component list yourself, everything is resolved automatically if your module is properly configured.
See ComponentFactoryResolver
, ComponentFactory
documentation.
By default you can not access module instance from component, but you could provide module yourself:
{
provide : 'module', //better use OpaqueToken
useExisting: forwardRef(() => AppModule),
}
Now can inject module into component: @Inject('module') module:any
Then use Reflect metadata package to extract module parameters.
Upvotes: 1