简体   繁体   English

有没有办法动态改变 Angular 中属性的 href 元素

[英]Is there a way to dynamically change the href element of attribute in Angular

I have this piece of code in my HTML component.我的 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>

I requested an "item" object from an API and it has the property item.link and item.name.我从 API 请求了一个“项目”object,它具有 item.link 和 item.name 属性。 My problem is that from the API that I get, the value that I get from item.link might have full URL address to an item (something like "https://stackoverflow.com") or some short URL (like "www.google.com").我的问题是,从我得到的 API 中,我从 item.link 得到的值可能具有完整的 URL 地址到一个项目(类似于“https://stackoverflow.com”)或一些简短的 ZE6B391A8ZD2C4D45903DA(类似于“www. google.com”)。

My goal is just to be able to handle the differences in link given back by the API, so that when clicked, it goes to the right page.我的目标只是能够处理 API 返回的链接差异,以便在单击时转到正确的页面。

I would like for the href to update so that it adds the "https://" in front of links like "www.google.com" everytime it goes through items in the for loop.我希望更新href,以便每次遍历for循环中的项目时,它都会在“www.google.com”之类的链接前面添加“https://”。

I tried adding "//" in front of "item.link" in the a tag.我尝试在 a 标签中的“item.link”前面添加“//”。 It fixes the item.link when it's the short URL without the https but breaks the link with https already in item.link.当它是没有 https 的短 URL 时,它修复了 item.link,但在 item.link 中断开了与 https 的链接。

Any help would be much appreciated.任何帮助将非常感激。 :) Thanks in advance. :) 提前致谢。

Why not check if it already has https and then consuming it?为什么不检查它是否已经有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>

You can extend this, or write a custom function to check for other cases like http or if it already has :// and other edge cases.您可以扩展它,或编写自定义 function 以检查http等其他情况,或者它是否已经具有://和其他边缘情况。

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

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