【发布时间】:2018-05-06 05:43:06
【问题描述】:
我有这个 plunker 示例 https://embed.plnkr.co/RtZvxv2rPFpLPZGndS0g/,我在其中动态创建了两个组件:ContentComponent 和 HeaderComponent。我想像这样在 ContentComponent 模板中引用 HeaderComponent 选择器:
ngOnInit() {
this.template = "<div>This is the {{ name }}</div><app-header></app-header>";
this.compileTemplate();
}
不幸的是,这不起作用,编译器抱怨:app-header 不是已知元素。
有人知道如何解决这个问题吗?是否有另一种方法可以获得相同的最终结果?
【问题讨论】:
-
你不能在运行时添加这样的 Angular “东西”——只能是纯 HTML。对于你想要的,你需要在运行时编译一个组件。见stackoverflow.com/questions/38888008/…
-
@yurzui 的解决方案有帮助吗?
-
终于成功了!非常感谢@yurzui!
-
感谢@AngularInDepth.com 教我如何使用动态组件。今天你可以用 Angular 做的事情真是太棒了。 blog.angularindepth.com/…
标签: angular dynamic nested components