-2

Is there a way in angular 5 to add the prefix http automatically if res.MyWebsiteURL do not contains it.

I would like to have a generic way to do it since I'll use at many place in the project.

<a  target="_blank" href="http://{{res.MyWebsiteURL}}">Visit My Website</a>

Is there a way to do it throught a Directive ?

Thanks a lot

Jean-Francois
  • 1,899
  • 4
  • 35
  • 73

3 Answers3

4

I did a PipeTransform
With a PipeTransform, you can modify a string element as needed. In my case, I wanted to determine if http prefix was include in the url or not. If it's not include, I'll inlcude it.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'linkHttp'
})
export class LinkHttpPipe implements PipeTransform {
  transform(href: string) {
    return href.startsWith("http://") || href.startsWith("https://") ? href : "http://" + href
  }
}

Here is how to use it

<a  target="_blank" href="{{res.MyWebsiteURL | linkHttp}}">Visit My Website</a>

Special thanks to JBNizet for the help

Jean-Francois
  • 1,899
  • 4
  • 35
  • 73
2

In my case this worked fine.

component.html:

<a [href]="getSubdomainLink(element)" target="_blank"> 
{{element.subDomain}} </a> 

component.ts:

getSubdomainLink(element: any) {
    return String(element.subDomain).startsWith('http') ? 
    element.subDomain : 'http://' + element.subDomain;
}   
Bhargavi
  • 233
  • 3
  • 11
0

Use double forward slash:

<a [href]="'//' + url">link</a>
Christian
  • 2,676
  • 3
  • 15
  • 25