angular - 动态创建组件呈现为同级
问题描述
组件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 内。我可以知道为什么吗?
解决方案
您的代码中发生的情况是,通过{ read: ViewContainerRef }
在div
元素上使用,您基本上将其转换为 a ViewContainer
which,顾名思义,它只是其他视图的容器。A它不会在页面上呈现,它只是显示它包含的视图。ViewContainer
您可以在此处阅读有关主机视图、嵌入式视图和ViewContainer
API 的更多信息。
这是上述文章的 TLDR。
当然,任何元素都可以ViewContainer
作为<ng-container #viewcontainer></ng-container>
.
所以,如果你想让你的组件在 div 中呈现,你必须这样做:
<div class="card-content">
<ng-container #sectionContainer></ng-container>
</div>
推荐阅读
- reactjs - document.getElementById(...).getElementsByTagName 不是函数
- google-closure-library - plovr 是否支持最新的闭包库?
- lc3 - 我如何输出用户输入字符串
- javascript - 如何在发送后立即从 RabbitMQ 中的队列中删除消息
- dart - 像 Excel 单元格一样的小部件(可以输入公式,显示的文本是公式的结果)?
- javascript - 如何从作为地图列表的 jquery ajax 响应中检索数据?
- django - Django Admin 查看表子集
- swift - Swift:将base64转换为图像不起作用
- c# - 如何从后台任务在主应用程序上执行功能
- google-maps - google chart geochart 可以免费使用吗?