Can we load component dynamically in Angular 2 using it's selector?
Lets say we have a component like below,
@Component({
moduleId: module.id,
selector: 'my-component',
templateUrl: 'my-component.html',
styleUrls: ['my-component.css']
})
export class MyComponent{
}
Can we load this dynamically into a container using it's selector my-component
<div #container ></div>
LoadComponent(selector: string){
// Load using selector?
}
There may be a need of exporting components in the NgModule and importing the NgModule where we want to load it.
Not sure on how to achieve this, any pointers in right direction would be very helpful.
Thanks in advance!!
Well I was able to resolve this using below,
constructor(private _compiler: Compiler) {}
loadComponent = (selector: string, module: any): void => {
this._compiler.compileModuleAndAllComponentsAsync(module).then(_module => {
let _componentFactories = _module.componentFactories.filter(_c => {
// here I am using the selector
return _c.selector === selector;
});
// check if component is available in the module
if (!!_componentFactories && _componentFactories.length > 0) {
self.testComponentContainer.clear();
self.testComponentContainer.createComponent(_componentFactories[0]).instance;
}
});
}
Hope it helps someone.. !!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With