我的应用程序中有10个组件,而我调用Home路由我希望根据Home服务响应加载动态组件。
首页组件
代码将执行,如, 家庭组件 - >呼叫HTTP服务 - >返回数组组件名称的列表名称 [例如]
答案 0 :(得分:4)
您是否看过关于dynamic component loading的文档?它显示了如何动态地将组件插入DOM中。
更具体地说,您需要注意以下几点:
1)定义将插入组件的锚点
您可以使用模板变量(#content
)执行此操作:
@Component({
template: `
<nav>...</nav>
<!-- This is where your components will be inserted -->
<div class="container" #content></div>
<footer>...</footer>
`
})
export class MyComponent {
@ViewChild('content', {read: ViewContainerRef}) content: ViewContainerRef;
constructor(private componentFactory: ComponentFactoryResolver) { }
ngAfterViewInit() {
this.loadComponents();
}
loadComponents() {
// Here, fetch the components from the backend
// and insert them at the anchor point.
}
}
2)获取组件CLASSES以插入并将其添加到DOM
问题是你的后端会将组件名称作为字符串返回,但ComponentFactoryResolver
需要类。
您需要将组件名称映射到实际的类。您可以使用自定义对象:
import {Widget1Component} from '../widget/widget1.component';
import {Widget2Component} from '../widget/widget2.component';
const componentsRegistry = {
'Widget1Component': Widget1Component
'Widget2Component': Widget2Component
};
现在loadComponents()
方法更容易编写:
loadComponents() {
// Fetch components to display from the backend.
const components = [
{ name: 'widget1', componentName: 'Widget1Component' },
{ name: 'widget2', componentName: 'Widget2Component' }
];
// Insert...
let componentClass, componentFactory;
for (let c of components) {
// Get the actual class for the current component.
componentClass = componentsRegistry[c.componentName];
// Get a factory for the current component.
componentFactory = this.componentFactory.resolveComponentFactory(componentClass);
// Insert the component at the anchor point.
this.content.createComponent(componentFactory);
}
}
3)不要忘记将动态组件添加到entryComponents
必须将动态加载的组件添加到其NgModule的entryComponents
数组中:
@NgModule({
// ...
entryComponents: [Widget1Component, Widget2Component, ...]
// ...
})
export class AppModule{ }