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

时间:2016-04-29 06:47:21

标签: 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-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}}>

2 个答案:

答案 0 :(得分:1)

您可以使用

之类的组件

<强> beta.17

@Component({
  selector: 'dcl-wrapper',
  template: '', //`<div #target></div>`
})
export class DclWrapper {
  // alternative way of getting a `ViewContainerRef` for an element inside the view instead of the host itself
  //@ViewChild('target', {read: ViewContainerRef}) target;

  constructor(private dcl:DynamicComponentLoader, private target:ViewContainerRef) {}
  @Input() type;

  ngOnChanges() {
    if(this.cmpRef) {
      throw 'currently changing type after the component was added is not supported'
    }
    this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
      this.cmpRef = cmpRef;
    });
  }
}

Plunker beta.17

<强> !! &lt; = beta.15语法!!

@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}
  @Input() type;

  ngOnChanges() {
    if(this.cmpRef) {
      this.cmpRef.dispose();
    }
    this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
      this.cmpRef = cmpRef;
    });
  }
}

(来自Angular 2 dynamic tabs with user-click chosen components

然后在您的组件中使用它

@Component({  
  directives: [DclWrapper],
  template: `
  <dcl-wrapper [type]="types[node.type]"></dcl-wrapper>
`})
export class ParentComponent {
  types = {
    application: PmApplicationComponent,
    proxy: PmProxyComponent,
    part: PmPartComponent,
    certificate: PmCertificateComponent,
    portal: PmPortalComponent,
  };
}

您不能对添加DynamicComponentLoader的组件使用[node]="node"之类的绑定,但您可以将数据传递给DclWrapper并将数据强制传递给包装组件。如果这种方法对您来说很有意思,我可以再详细说明一下。

答案 1 :(得分:0)

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

如果这不可行,我只想创建一个超级组件

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

并在此组件内部设置开关。那么至少你不需要一直重复它。