Angular 2:基于服务响应加载组件

Yat*_*tel 3 angular

我的应用程序中有 10 个组件,当我调用 Home 路由时,我想根据 Home 服务响应加载动态组件。

首页组件

在此处输入图片说明

代码将像 Home 组件一样执行 -> 调用 HTTP 服务 -> 返回数组组件名称的列表名称 [例如]

在此处输入图片说明 -> 现在我想在内容区域中附加 2 个组件

页面将呈现如下 在此处输入图片说明

Ang*_*hef 5

您是否看过有关动态组件加载的文档?它展示了如何将组件动态插入到 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.
  }
}
Run Code Online (Sandbox Code Playgroud)

2)获取要插入的组件CLASSES并添加到DOM中

问题是您的后端以字符串形式返回组件名称,但ComponentFactoryResolver需要

您需要将组件名称映射到实际类。您可以为此使用自定义对象:

import {Widget1Component} from '../widget/widget1.component';
import {Widget2Component} from '../widget/widget2.component';
const componentsRegistry = {
  'Widget1Component': Widget1Component
  'Widget2Component': Widget2Component
};
Run Code Online (Sandbox Code Playgroud)

现在该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);
  }
}
Run Code Online (Sandbox Code Playgroud)

3)不要忘记添加动态组件 entryComponents

动态加载的组件必须添加到它们的 NgModuleentryComponents数组中:

@NgModule({
  // ...
  entryComponents: [Widget1Component, Widget2Component, ...]
  // ...
})
export class AppModule{ }
Run Code Online (Sandbox Code Playgroud)