如何在 Angular 2 中动态加载和显示包含 routerLink 指令的 html? [英] How do I dynamically load and display html which contains routerLink directives in Angular 2?

查看:25
本文介绍了如何在 Angular 2 中动态加载和显示包含 routerLink 指令的 html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Angular 2 组件,它根据某些用户操作从数据库加载 html.html 包含带有相对路径的锚标记.鉴于我不希望在用户单击链接时重新加载整个应用程序,我正在尝试使用 routerLink 指令;但是,由于此 html 是动态加载的,因此不会处理 routerLink.html 将不包含任何其他角度指令.实现这一目标的最简单方法是什么?请参阅下面的示例.

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

推荐答案

我会保持简单.

如果可能,用 标签替换链接,并使用 CSS 使它们看起来像链接.将它们重写为 <span data-link="/some-route">link</span>.

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.

从技术上讲,您实际上不必将标签重写为 .<a routerLink=""> 也可以工作,因为它没有 href 属性来触发浏览器 URL 更改.只需阅读 routerLink 属性而不是我的示例.

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.

这篇关于如何在 Angular 2 中动态加载和显示包含 routerLink 指令的 html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆