首页 > 解决方案 > 动态创建组件呈现为同级

问题描述

组件about-me是动态创建并注入到 a 中的,div但该组件不会在div标签内呈现,而是呈现为兄弟姐妹。如何在div标签内渲染动态创建的组件。

代码:

home.component.html

<div class="card-content" #sectionContainer></div>

home.component.ts

...
@ViewChild('sectionContainer', {static: true, read: ViewContainerRef }) sectionEntry: ViewContainerRef;
...
  loadAboutMeComponent() {
    this.store.dispatch(new OpenSection());
    this.sectionEntry.clear();
    const factory = this.resolver.resolveComponentFactory(AboutmeComponent);
    const componentRef = this.sectionEntry.createComponent(factory);
  }

安慰:

在此处输入图像描述

该组件渲染得非常好,但不在 div 内。我可以知道为什么吗?

标签: angular

解决方案


您的代码中发生的情况是,通过{ read: ViewContainerRef }div元素上使用,您基本上将其转换为 a ViewContainerwhich,顾名思义,它只是其他视图容器。A它不会在页面上呈现,它只是显示它包含的视图。ViewContainer

您可以在此处阅读有关主机视图嵌入式视图ViewContainerAPI 的更多信息。

这是上述文章的 TLDR

当然,任何元素都可以ViewContainer作为<ng-container #viewcontainer></ng-container>.

所以,如果你想让你的组件在 div 中呈现,你必须这样做:

<div class="card-content">
 <ng-container #sectionContainer></ng-container>
</div>

推荐阅读