如何定义注入动态组件的位置?

How to define place where dynamic components would be injected?

我的组件是动态注入的。但是如何定义它们在没有任何包装的情况下的位置呢?

import { Component, ViewContainerRef, ComponentResolver } from '@angular/core';

  constructor(
    private apiService: ApiService,
    private viewContainerRef: ViewContainerRef,
    private componentResolver: ComponentResolver) {
  }

  create() {
    this.componentResolver.resolveComponent(PieChart).then((factory) => {
      this.viewContainerRef.createComponent(factory);
    });
  }

我想将它们注入一些 DIV。

<div class="someClass"> 
<!--How inject them here?  -->
</div>

有两种方法:

  • 像您的问题一样注入ViewContainerRef,然后在该组件下方添加新组件

  • 使用组件模板中的目标元素和模板变量,如 <div #target></div>@ViewChild('target', {read: ViewContainerRef}) viewContainerRef:ViewContainerRef; 来获取此 <div>ViewContainerRef。添加的元素在下面再次添加 <div>

createComponent() 允许传递索引。默认情况下,新组件总是添加在末尾,但如果您传递索引,它会插入到此位置。
(未测试)使用索引 0 您应该能够在目标元素之前添加新元素。
如果您将多个组件添加到同一个 ViewContainerRef,您可以传递一个索引以在之前添加的元素之前插入新组件。

在最终版本中,ComponentResolver 已被弃用。相反,我们可以使用 Compiler API 来创建 ComponentFactory。

但是我们现在如何才能做到这一点?

我找到这篇文章 http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2-rc-5/ 但编译器没有方法 compileComponentAsync。