【问题标题】:How to define place where dynamic components would be injected?如何定义注入动态组件的位置?
【发布时间】:2016-11-22 09:17:06
【问题描述】:

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

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>

【问题讨论】:

  • 我不太明白你的问题,但这听起来与我在stackoverflow.com/questions/36325212/…中演示的相似
  • 但是如何定义位置,新组件在哪里?类似 的东西用于路由。
  • 在链接的答案中,组件被添加到 &lt;dcl-wrapper&gt; 元素内。

标签: angularjs dynamic typescript angular components


【解决方案1】:

有两种方式:

  • 在您的问题中注入ViewContainerRef,然后在此组件下方添加新组件

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

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

【讨论】:

  • 使用此代码的创建函数应该如何:@ViewChild('target', {read: ViewContainerRef}) viewContainerRef:ViewContainerRef ?
  • 不确定你的意思。您在问题中使用的功能应该可以工作。
  • 非常感谢!你真的帮了我。
【解决方案2】:

在最终版本中,不推荐使用 ComponentResolver。相反,我们可以使用 Compiler API 来创建 ComponentFactory。

但是我们现在怎么做呢?

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

【讨论】:

    猜你喜欢
    • 2017-08-12
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多