简体   繁体   English

如何在 angular 中绑定锚标签

[英]How can i bind a anchor tag in angular

in my angular application, i am trying to bind a string to a div using angular innerHTML, Here is the string在我的 angular 应用程序中,我正在尝试使用 angular innerHTML 将字符串绑定到 div,这是字符串

sample = "<a routerLink='/tags/name/'>Test</a>  smod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam";
    

here is the html page这是 html 页面

<p [innerHTML]="sample"></p>

Now my problem is that the anchor tag is now working, it only displays the Test but i cant click it to navigate to the other page, how can i make it to work.现在我的问题是锚标记现在正在工作,它只显示Test但我无法单击它导航到另一个页面,我怎样才能让它工作。

The routerLink selector is an Angular specific property, which means it probably won't work when it's bound as raw HTML in an element. routerLink选择器是 Angular 特定属性,这意味着当它绑定为元素中的原始 HTML 时,它可能无法工作。

You're better off doing something like this:你最好做这样的事情:

HTML HTML

<p>
  <a [routerLink]="myLink">{{myLinkLabel}}</a> 
  {{myLabel}}
</p>

Typescript Typescript

myLink = ['/something/here'] // Links have to be arrays
myLinkLabel = 'Test'
myLabel = 'smod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam'

I think the best approach is to sanitize the html and use a directive to handle the click event.我认为最好的方法是清理 html 并使用指令来处理点击事件。

Look at that answer https://stackoverflow.com/a/49006667/5264995 .看看那个答案https://stackoverflow.com/a/49006667/5264995

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM