Angular 6 - <a> href被添加到基本URL

9

我有一个用户列表,显示在表格中,每个用户都有一个链接可以被访问。

<div class="inline-icon-text">
  <small class="text-muted d-md-none mr-3">Link</small>
  <a [attr.href]="candidate.url" target="_blank" [title]="candidate.url">
    <i class="material-icons">open_in_new</i>
  </a>
</div>

问题是,当我检查链接元素时,它指向正确的地址,但在点击后会附加到应用基本URL上。
<a _ngcontent-c15="" target="_blank" href="www.test.sk" title="www.test.sk">...</a>

点击后,它会在新标签页中打开,网址为localhost:4200/www.test.sk

我错过了什么?


这可能会对您有所帮助:https://medium.com/@adrianfaciu/using-the-angular-router-to-navigate-to-external-links-15cc585b7b88 - Jayampathy Wijesena
1个回答

23

无论你的应用程序使用什么协议,始终在绝对外部链接前加上协议或 // 缩写表示使用 http://https://

<div class="inline-icon-text">
  <small class="text-muted d-md-none mr-3">Link</small>
  <a [attr.href]="'//' + candidate.url" target="_blank" [title]="candidate.url">
    <i class="material-icons">open_in_new</i>
  </a>
</div>

默认情况下,浏览器将URL视为相对路径,以便在应用程序导航中使用。

顺便提一下,这种行为并非特定于Angular;其他框架和普通网站的行为完全相同。


这只是设置一个字符串属性,所以 + 表示通常的 JS 字符串连接。routerLink 不同,因为它是一个带有附加逻辑的指令。希望对你有帮助。 - Tomasz Błachut
2
你能告诉我为什么会发生这种情况吗? - Ali Abbaszade
@TomaszBłachut 我的意思是,为什么我在地址前面不加“//”时,URL会自动更改? - Ali Abbaszade
@AliAbbaszade URL语法复杂,许多部分可以省略。简单来说,默认行为与您的终端相同:cd projects进入子目录,指向www.example.com的链接指向相对于当前资源的子资源。现在,单斜杠/使URL相对于计算机根目录,双斜杠//使URL相对于互联网根目录,如果这样的东西甚至存在的话。 https://en.wikipedia.org/wiki/URL HTH - Tomasz Błachut
1
@TomaszBłachut 如果用户在输入中写入例如 https://google.com,那么 a href 标签会有什么反应? 因为我已经添加了您的答案,并且它适用于 www.somethingsomething.com,但是如果我添加 https://something.com,则链接将无法工作。 您有任何想法吗? - TheCoderGuy
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接