VVildVVolf VVildVVolf - 1 month ago 32
TypeScript Question

Angular 2.1 append component dynamicly inside directive

I am a beginner in the angular 2.1. I Want to decorate some elements for the automatical translation and I am going to use a directive, it have to look like:

<span customDirectiveTranslation="translateble">{{translateble}}</span>


or just

<span customDirectiveTranslation>{{translateble}}</span>


I can use the Renderer inside directive class (createElement), but by this way I can append only simple elements like span.

how can I render component inside another component by custom directive?
Thanx

Answer
constructor(
    private target:ViewContainerRef, 
    private componentFactoryResolver: ComponentFactoryResolver, 
    private compiler: Compiler) {}

ngAfterViewInit() {
  this.createComponent();
}

createComponent() {
    let factory = this.componentFactoryResolver.resolveComponentFactory(MyDynamicComponent);
    this.cmpRef = this.target.createComponent(factory)
}

See also Angular 2 dynamic tabs with user-click chosen components