Angular2,如何包含依赖于值的组件

Angular2,如何包含依赖于值的组件,angular,angular2-template,angular2-directives,Angular,Angular2 Template,Angular2 Directives,我有以下HTML代码: <pm-application [node]="node" *ngIf="node.type ==='application'"></pm-application> <pm-proxy [node]="node" *ngIf="node.type ==='proxy'"></pm-proxy> <pm-part [node]="node" *ngIf="node.type ==='part'"></pm-p

我有以下HTML代码:

<pm-application [node]="node" *ngIf="node.type ==='application'"></pm-application>
<pm-proxy [node]="node" *ngIf="node.type ==='proxy'"></pm-proxy>
<pm-part [node]="node" *ngIf="node.type ==='part'"></pm-part>
<pm-certificate [node]="node" *ngIf="node.type ==='certificate'"></pm-certificate>
<pm-portal [node]="node" *ngIf="node.type ==='portal'"></pm-portal>

它看起来不太好看,而且还有很多其他类型,所以列表会增加。有没有更简单的方法?比如:

<{{node.type}} [node]="node"><{{node.type}}>

您可以使用以下组件

测试版17

@组件({
选择器:“dcl包装器”,
模板:“”//``
})
出口级DclWrapper{
//为视图中的元素而不是主机本身获取“ViewContainerRef”的替代方法
//@ViewChild('target',{read:ViewContainerRef})目标;
构造函数(私有dcl:DynamicComponentLoader,私有目标:ViewContainerRef){}
@Input()类型;
ngOnChanges(){
if(this.cmpRef){
抛出“不支持在添加组件后当前更改类型”
}
this.dcl.loadNextToLocation(this.type,this.target)。然后((cmpRef)=>{
this.cmpRef=cmpRef;
});
}
}

!!{ this.cmpRef=cmpRef; }); } } (来自)

然后在您的组件中像这样使用它

@组件({
指令:[DclWrapper],
模板:`
`})
导出类ParentComponent{
类型={
应用:PmApplicationComponent,
代理:PmProxyComponent,
零件:PmPartComponent,
证书:PmCertificateComponent,
门户:PmPortalComponent,
};
}

您不能对添加的组件使用像
[node]=“node”
这样的绑定,但您可以将数据传递到
DclWrapper
,并强制将数据传递到包装的组件。如果您对这种方法感兴趣,我可以详细说明一下。

我不确定Angular 2中是否可以这样做,但在v1中,您可以在指令中使用restrict属性来使用css类或属性,而不是节点名

如果这是不可能的,我会创建一个超级组件

<pm-supercomponent [node]="node"/>


把开关放在这个部件里。那么,至少您不需要一直重复它。

因为DynamicComponentLoader已被弃用,所以我等待一个更稳定、文档更完整的解决方案。中介绍了当前的方法