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

查看:65
本文介绍了如何在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>';
   }
}

推荐答案

我只是保持简单.

如果可能,将链接替换为<span>标记,并使用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.

从技术上讲,您实际上不必将标签重写为<span>. <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天全站免登陆