Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 514
Dethariel Avatar asked Sep 07 '16 23:09

Dethariel


People also ask

What is difference between routerLink and routerLink?

What is the difference between [routerLink] and routerLink ? How should you use each one? They're the same directive. You use the first one to pass a dynamic value, and the second one to pass a static path as a string.

Is routerLink a directive?

In Angular, RouterLink is a directive for navigating to a different route declaratively. Router. navigate and Router. navigateByURL are two methods available to the Router class to navigate imperatively in your component classes.


1 Answers

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

like image 129
Günter Zöchbauer Avatar answered Oct 21 '22 22:10

Günter Zöchbauer