【问题标题】:Angular 2: Load Component Based on service responseAngular 2:基于服务响应加载组件
【发布时间】:2017-02-26 06:01:47
【问题描述】:

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

首页组件

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

-> 现在我想在内容区域添加 2 个组件

页面将呈现为

【问题讨论】:

标签: angular


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-05-07
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2017-09-05
    • 2017-11-10
    • 2018-02-15
    • 1970-01-01
    相关资源
    最近更新 更多