动态组件未加载到专利组件中

Dynamic component not loading inside patent component

我正在根据其类型创建动态组件。

使用上述结构,我创建了 ParagraphComponent 的父组件,如果您注意到 ranges 有一个 type,所以我想创建一个 LinkComponent

有什么问题?

LinkComponent 已创建但不在其父组件内部,它 在 ParagraphComponent.

之外创建
<rc-paragraph><p>This is paragraph</p></rc-paragraph>`
<app-link>/index.htm</app-link>

但其实应该是这样的,

<rc-paragraph>
    <p>This is paragraph <app-link>/index.htm</app-link></p>
</rc-paragraph>

下面是渲染组件的代码,

private renderReactiveContent(content, container: ViewContainerRef) {

    // resolve content['_type'] to factory
    var type: Type<any>;
    if (content instanceof Array) {
      type = this.contentMappings[content[0].type];
    } else {
      type = this.contentMappings[content.type];
    }
    if (!type) {
      return;
      // throw new ReferenceError(`No content mapping for type=${type}`);
    }

    const componentFactory: ComponentFactory<any> = this.componentFactoryResolver.resolveComponentFactory(type);
    const component = container.createComponent(componentFactory, container.length, this.injector);
    console.info('Component dynamically created ', component);

    // content lifecycle hook: notify of new values
    const cmpCreate = asContentCreate(component);
    cmpCreate.contentOnCreate(content);

    // render embedded content
    if (content && Object.keys(content).length > 0) {

      const cmpEmbeddable = asContentEmbeddable(component);
      if (cmpEmbeddable) {

        // render in the target element of ContentEmbeddable
        const childContainer = cmpEmbeddable.contentEmbeddable();

        Object.keys(content).forEach((key: string) => {
          const value = content[key];

          // XX: recursive rendering
          if (value instanceof Array) {
            value.forEach((v) => {
              this.renderReactiveContent(v, childContainer);
            });
          } else {
            this.renderReactiveContent(value, childContainer);
          }
        });

      } else {

        // fatal: embedded content must be hosted by ContentEmbeddable
        const cmpName = component.instance['constructor'].name;
        throw new TypeError([`Trying to render embedded content.`,
          `${cmpName} must implement interface ContentEmbeddable`].join(' '));

      }

    }
    component.hostView.detectChanges();
  }

我这里做错了什么,请帮忙。

如何 angular 注入视图是,如果您的主机是

<span #container><span>

然后它将注入为

<span><span>
<your-injected-view></your-injected-view>

因此,当您尝试注入父元素时,您的父元素是宿主元素,子元素被注入到它旁边,而不是它里面。

如何解决? 一种方法是使父容器内的元素成为宿主元素,而不是使父容器成为宿主。

<parent>
 <span #container></span>
</parent>

所以它将注入它作为

<parent>
  <span></span>
  <your-injected-view></your-injected-view>
</parent>

使用 <ng-container></ng-container> 注入视图并避免任何副作用总是好的。