如何在innerHTML中使用routerLink [英] How to use routerLink with innerHTML

查看:29
本文介绍了如何在innerHTML中使用routerLink的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Angular 6.我只想使用 innerHTML 创建一个动态路由.我尝试了以下代码,但它不起作用.在组件文件中,我在构造函数里面写了如下代码:

I am using Angular 6. I just want to create a dynamic route by using the innerHTML. I tried the following code but it is not working. In the component file, I wrote the following code inside the constructor:

this.anchor = "<a routerLink='login'>Dynamic Login</a>"

在模板文件中,我写了如下代码:

In the template file, I wrote the following code:

<div [innerHtml]="anchor"></div>

推荐答案

当我遇到和你一样的问题时,我使用了一个 hacky 解决方案,因为我没有找到更好的解决方案.在模板中,我有 span ,我在其中设置 innerHtml html 来自服务器,它可以有 a 标签以及任何其他格式的 html标签.所以解决方案是添加点击事件:

There is one hacky solution that I used when encountered same problem as you did since I didn't find anything better. In template I had span where I was setting innerHtml that html was coming from server and it could have a tag as well as any other formatting html tags. So the solution is to add click event:

<span [innerHtml]="customHtml" (click)="processLinks($event)"></span>

并在我们的 ts 文件中处理它们:

And in our ts file process them:

customHtml: string = 'Hey <a href="/help/">this is</a> a link';

// Don't forget to import and inject the router
constructor(private router: Router) {}

// ...

processLinks(e) {
  const element: HTMLElement = e.target;
  if (element.nodeName === 'A') {
    e.preventDefault();
    const link = element.getAttribute('href');
    this.router.navigate([link]);
  }
}

请注意,您可以对此处的链接进行任何操作,如果需要,您可以在导航到链接之前添加一些条件或转换链接.

Notice that you can do anything with the link here, if you need you can add some conditions or transform links before navigating to them.

希望有帮助.我知道这不是最好的解决方案,必须有更好的解决方案.但这就是我匆忙想到的.

Hope it helps. I know it's not the best solution, there must be something better. But that's what I came up with in a rush.

这篇关于如何在innerHTML中使用routerLink的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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