如何在innerHTML中使用routerLink [英] How to use routerLink with innerHTML
问题描述
我正在使用Angular6.我只想使用 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屋!