Angular - 通过名称(不是类型)创建动态组件

时间:2017-06-15 12:50:29

标签: javascript angular

我有一个类型的数组:types = [C3,C1,C2];其中C1,C2,C3是类:

export class C1 {}        //... C2 and C3

@Component({
  selector: 'c2',         //... C2 and C3
  template: `<h2>c2</h2>` //... C2 and C3

})

App.ts

@Component({
  selector: 'my-app',
  directives: [Tabs],
  template: `
   <my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
  // The list of components to create tabs from
  types = [C3,C1,C2];
}

<my-tabs>

@Component({
  selector: 'my-tabs',
  directives: [DclWrapper],
  template: `

  <div *ngFor="let tab of tabs">
    <dcl-wrapper [type]="tab"></dcl-wrapper>
  </div>
`
})
export class Tabs {
  @Input() tabs;
}

<dcl-wrapper>

@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;

  constructor(private componentFactoryResolver: ComponentFactoryResolver,
      private cdRef:ChangeDetectorRef) {}

  updateComponent() {
    let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
    this.cmpRef = this.target.createComponent(factory)
    this.cdRef.detectChanges();
  }

  ngOnChanges() {
   this.updateComponent();
  }


  ngOnDestroy() {
     console.log('ngOnDestroy');
      this.cmpRef.destroy();
    }    
  }
}

这一切都正常,我确实看到了预期的结果:

enter image description here

问题:

目前,数组本身包含类型:

types = [C3,C1,C2];

但是,让我们说数组包含类型名称

types = ['C3','C1','C2'];

为了让'C3'成为C3,我应该在代码中更改哪些内容?

PLUNKER

0 个答案:

没有答案