I have this piece of code in my HTML component.
<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. 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").
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.
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.
I tried adding "//" in front of "item.link" in the a tag. It fixes the item.link when it's the short URL without the https but breaks the link with https already in item.link.
Any help would be much appreciated. :) Thanks in advance.
Why not check if it already has https and then consuming it?
<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.