How do I dynamically load and display html which contains routerLink directives in Angular 2?
Asked Answered
C

1

3

I have an Angular 2 component which, on some user action, loads html from a database. The html contains anchor tags with relative paths. Given that I don't want the whole application to reload when the user clicks the link, I am trying to use the routerLink directive; however, since this html is loaded dynamically, the routerLink is not processed. The html will not contain any other angular directives. What is the simplest way to achieve this? See my example below.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
             <p><a (click)="GetTextFromDatabase()">Get data from database</a> which should contain a <a routerLink="/some-route">working link</a></p>
             <div [innerHTML]="data"></div>
             <router-outlet></router-outlet>`,
})
export class AppComponent  {
   name: string = 'Angular';
   data: string;

   private GetTextFromDatabase(): void {
      this.data = '<p>here is my paragraph containing a <a routerLink="/some-route">link</a>';
   }
}
Crumpled answered 6/7, 2017 at 13:11 Comment(3)
Why you cant not put explicit the anchor with a directive *ngIf and when the event click is invoked put true the anchorOutbreed
the problem is that the html is generated at run time rather than design time, which means that any angular directives are not processedCrumpled
Look at this angular.io/api/common/NgTemplateOutletOutbreed
B
3

I would just keep it simple.

If possible replace the links with <span> tags and use CSS to make them look like links. Rewrite them as <span data-link="/some-route">link</span>.

In your template use a click listener:

<div [innerHTML]="data" (click)="onDataClick($event)"></div>

In your component read the click target:

public onDataClick(event: Event) {
      if(event.target.tagName.toLowerCase() === 'span') {
          const link = event.target.getAttribute('link');
          // call the router to navigate to the new route
          console.log(link)
      }
}

That should be enough to get the links working.

Technically, you don't really have to rewrite the tags to <span>. The <a routerLink=""> would work as well since it has no href attribute to trigger a browser URL change. Just read the routerLink attribute instead of my example.

Billye answered 6/7, 2017 at 13:41 Comment(1)
data- attributes are stripped by the innerHTML directive. I had to add a pipe to bypass this.Crumpled

© 2022 - 2024 — McMap. All rights reserved.