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

旧时模样 提交于 2020-02-22 06:21:45

问题


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>';
   }
}

回答1:


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.



来源:https://stackoverflow.com/questions/44949958/how-do-i-dynamically-load-and-display-html-which-contains-routerlink-directives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!