0

I have an array of types : types = [C3,C1,C2]; where C1,C2,C3 are classes :

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();
    }    
  }
}

This all working fine and I do see the expected results :

enter image description here

Question:

Currently the array contains the types themselves :

types = [C3,C1,C2];

But let's say that the array contains the type name :

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

What should I change in my code in order for 'C3' to become a C3 ?

PLUNKER

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 3
    https://stackoverflow.com/questions/40528592/ng2-dynamically-creating-a-component-based-on-a-template – yurzui Jun 15 '17 at 12:52
  • @yurzui Indeed , but the answer there mentions that I must use a dictionary of name and type ( for minification). So I ask - is there a way to "resolve" the string to a type without also mentioning a type ? (which is redundant and non-dynamic solution) – Royi Namir Jun 15 '17 at 12:56

0 Answers0