目标是从列表中动态加载组件并使用关联的标签显示它们。 我制作标签的方法基于本教程:https://juristr.com/blog/2016/02/learning-ng2-creating-tab-component/和
如果您想通过将每个组件包装在选项卡中来对其进行硬编码,这非常有用。遗憾的是,当尝试动态加载ng-content中的组件时,这种方法失败了。
我确实看到yurzui的回答,Creating a angular2 component with ng-content dynamically这与我想要完成的事情非常接近。
下面的代码块(参见上面的链接)是我可以弥补这个例子和我之间的差距的地方。我不知道在我的例子中传递给createComponent()的params。在这里放置这段代码,目前我有createTab指令来保存这段代码。如果我把指令放在"标签"我继续打开元素或 "标签"元件。
add() {
const bodyFactory = this.cfr.resolveComponentFactory(CardBodyComponent);
const footerFactory = this.cfr.resolveComponentFactory(CardFooterComponent);
let bodyRef = this.vcRef.createComponent(bodyFactory);
let footerRef = this.vcRef.createComponent(footerFactory);
const cardFactory = this.cfr.resolveComponentFactory(CardComponent);
const cardRef = this.vcRef.createComponent(
cardFactory,
0,
undefined,
[
[bodyRef.location.nativeElement],
[footerRef.location.nativeElement]
]
);
this.components.push(bodyRef, cardRef, footerRef);
}
带回家的消息是我想把动态创建的组件放在标签的ng-content位置。然后标签ng-content将由标签填充。
这是我为实现这一目标所做的微弱尝试。 http://plnkr.co/edit/ieSNgqusP0rwZBMQSvYQ?p=preview