你看过关于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{ }