1

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

1 Answer 1

2
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

Sign up to request clarification or add additional context in comments.

10 Comments

but in the link some code of my directive, I have got an exception: EXCEPTION: Error in ./TagComponent class TagComponent - inline template:0:0 caused by: No component factory found for TestComponentComponent
You need to add TestComponentComponent to entryComponents in @NgModule() so that a factory is created.
O_O I cannot belive
By this way the new component will be created after (or before) the directive-marked component, can i put the new component inside?
No, only as sibling. You need a ViewContainerRef of an element inside the element, then you can add it inside.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.