角度2:基于服务响应的负载组件 [英] Angular 2: Load Component Based on service response
问题描述
我的应用程序中有10个组件,当我调用本地路由"时,我想基于本地服务响应来加载动态组件.
I have 10 components in my app, while I call Home route I want to load dynamic components base on Home service response.
主页组件
代码将像主页组件->调用HTTP服务->返回我数组组件名称的列表名称[例如]
Code will execute like, Home component - > Call HTTP Service -> returns me list name of array component name [e.g ]
->现在我要在内容区域中添加2个组件
-> Now I want to append 2 components in content area
页面将呈现为
推荐答案
Have you seen the doc about dynamic component loading? It shows how you can dynamically insert components into the DOM.
更具体地说,您需要注意一些事项:
More specifically, there are a few things you need to pay attention to:
1)定义要在其中插入组件的锚点
您可以使用模板变量( #content
)来做到这一点:
You can do that with a template variable (#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
需要的是类.
The problem is that your backend returns component names as strings, but ComponentFactoryResolver
expects classes.
您需要将组件名称映射到实际的类.您可以为此使用自定义对象:
You need to map component names to actual classes. You could use a custom object for this:
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
3) Do not forget to add the dynamic components to entryComponents
必须将动态加载的组件添加到其NgModule的 entryComponents
数组中:
Dynamically loaded components have to be added to their NgModule's entryComponents
array:
@NgModule({
// ...
entryComponents: [Widget1Component, Widget2Component, ...]
// ...
})
export class AppModule{ }
这篇关于角度2:基于服务响应的负载组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!