我们可以使用它的选择器在 Angular 2 中动态加载组件吗?
假设我们有一个如下所示的组件,
@Component({
moduleId: module.id,
selector: 'my-component',
templateUrl: 'my-component.html',
styleUrls: ['my-component.css']
})
export class MyComponent{
}
我们可以使用它的选择器 my-component
将它动态加载到容器中吗?
<div #container ></div>
LoadComponent(selector: string){
// Load using selector?
}
可能需要在NgModule中导出组件,在我们要加载的地方导入NgModule。
不确定如何实现这一点,任何正确方向的指示都会非常有帮助。
提前致谢!!
最佳答案
好吧,我能够使用下面的方法解决这个问题,
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;
}
});
}
希望对某人有所帮助..!!!
关于angular - 使用选择器在 Angular 2 中动态加载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39020164/