首页 > 解决方案 > 动态组件未加载到专利组件内

问题描述

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

使用上面的结构,我创建了父组件,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-dynamic-components

解决方案


角度注入视图的方式是,如果您的主机是

<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>用于注入视图并避免任何副作用总是很好的。


推荐阅读