gpt4 book ai didi

angular - 使用选择器在 Angular 2 中动态加载组件

转载 作者:太空狗 更新时间:2023-10-29 18:02:49 24 4
gpt4 key购买 nike

我们可以使用它的选择器在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com