3

I am trying to dynamically generate markup in a component, where the markup to be created involves other custom components. Something along the lines of:

<my-component></my-component>

and in myComponent.ts

ngOnInit(){
    const el: HTMLElement = this.elementRef.nativeElement;

    let labels = ['one', 'two', 'three'];
    labels.forEach((label) => {
        let b = document.createElement('my-subcomponent');
        el.appendChild(b);
    });
}

mySubcomponent.html template:

<span>test</span>

The children <my-subcomponent> elements do render into the markup, but bare, without the <span> template. I think I am missing an equivalent of Angular1's $compile service, or I am doing the right code in wrong lifecycle moment. Would appreciate someone shed some light on me.

1 Answer 1

2

Angular2 doesn't process bindings or matching component or directive selectors in any way for dynamically added HTML. Angular2 only processes HTML added statically to components templates.

You can add components dynamically for example like shown in Angular 2 dynamic tabs with user-click chosen components

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

3 Comments

Thanks for the link. In this strategy, is there a way to attach attributes to C1, C2, C3 (in the plunkr) so that they would accept them as inputs?
No, you can't use inputs and outputs in dynamically added components. The linked answer shows how to pass data in and out imperatively though.
Thanks for your explanation

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.