9

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?

Dethariel
  • 3,394
  • 4
  • 33
  • 47
  • I'm not sure if I understood what you want to do here but, by your Plunker, I guess your issue is that the `login` link isn't working, right? If so, why are you using the `routerLink` inside your localization instead of using it in your template? – brians69 Sep 08 '16 at 02:51
  • Hey.. How did you solve the issue to dynamically add routerlink to anchor tag from type script class.? I tried hard to create dynamic component but no success. Please help me out. – Meenakshi Kumari Aug 11 '17 at 07:17
  • @MeenakshiKumari I didn't go down that path eventually, but restructured my code to not have dynamic links instead – Dethariel Aug 16 '17 at 18:53
  • Actually I did the same.. Thanks.. – Meenakshi Kumari Aug 18 '17 at 10:07

1 Answers1

6

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

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567