Search code examples
angulartypescriptangular2-routingangular2-directives

How to make Angular 2 pick up dynamically added routerLink directive


As seen in this plunker, I'm dynamically adding an HTML to one of my elements, which boils down to this:

@Component({
    selector: 'my-comp',
    template: `<span [innerHTML]="link"></span>`,
}) export class MyComponent {
    private linkContent = '<a routerLink="/my-route">GoTo Route</a>';
    private link;

    constructor(sanitizer: DomSanitizer) {
        this.link = sanitizer.bypassSecurityTrustHtml(linkContent);
    }
}

This results in <a routerLink="/my-route">GoTo Route</a> being added to the DOM, but Angular knows nothing about the routerLink directive on this element, and does not "bind" to it. So, when you click the link, it results in complete reload with re-bootstrap (which doesn't work in plunk, it just gives a 404).

Question: how to tell angular to go through the DOM (or its part, or even a single element) and perform component initialization if needed?


Solution

  • Angular2 doesn't process HTML added dynamically in any way except sanitization.

    Passing '<a routerLink="/my-route">GoTo Route</a>' to innerHTML is doing exactly this, passing this string to the DOM, but nothing else. There is no routerLink directive being instantiated or applied.

    If you need to add HTML dynamically that uses Angular2 bindings, directives, or components, you can add the HTML to a components template, and add this component dynamically using ViewContainerRef.createComponent() like demonstrated for example in Angular 2 dynamic tabs with user-click chosen components