Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating dynamic markup involving custom HTML elements in Angular 2

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.

like image 609
user776686 Avatar asked Apr 19 '26 09:04

user776686


1 Answers

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

like image 118
Günter Zöchbauer Avatar answered Apr 21 '26 23:04

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!