【问题标题】:Is there a way to dynamically change the href element of attribute in Angular有没有办法在Angular中动态更改属性的href元素
【发布时间】:2021-11-22 19:30:11
【问题描述】:

我的 HTML 组件中有这段代码。

      <ul>
        <li *ngFor="let item of items">
          <a href="{{item.link}}" target="_blank">{{item.name}}</a>
          <span *ngIf="item.Description" class="text-muted"> {{item.Description}}</span>
        </li>
      </ul>

我从 API 请求了一个“项目”对象,它具有属性 item.link 和 item.name。 我的问题是,从我获得的 API 中,我从 item.link 获得的值可能具有项目的完整 URL 地址(例如“https://stackoverflow.com”)或一些短 URL(例如“www. google.com”)。

我的目标只是能够处理 API 返回的链接的差异,以便在单击时转到正确的页面。

我希望更新 href 以便在每次遍历 for 循环中的项目时在“www.google.com”等链接前面添加“https://”。

我尝试在 a 标签中的“item.link”前面添加“//”。当 item.link 是没有 https 的短 URL 时,它会修复 item.link,但会破坏 item.link 中已有 https 的链接。

任何帮助将不胜感激。 :) 提前致谢。

【问题讨论】:

  • 我建议只使用库。手动操作用户输入(尤其是链接时)可能会导致安全相关问题。

标签: javascript html angular


【解决方案1】:

为什么不检查它是否已经有https 然后消费它?

<ul>
        <li *ngFor="let item of items">
          <a href="{{item.link.startsWith('https://') ? item.link : `https://${item.link}`}}" target="_blank">{{item.name}}</a>
          <span *ngIf="item.Description" class="text-muted"> {{item.Description}}</span>
        </li>
</ul>

您可以扩展它,或者编写一个自定义函数来检查其他情况,例如http,或者它是否已经有:// 和其他边缘情况。

【讨论】:

    猜你喜欢
    • 2014-12-17
    • 2012-04-01
    • 2022-11-30
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    相关资源
    最近更新 更多