1

I am trying to redirect to external url using anchor tag but angular is trying to route it inside the application. Is there anyway to redirect to external url without using directive and without adding http:// or https:// to it.

Example:

<a href="{{ link }}"
rel="noopener noreferrer"
target="_blank">
    {{ link }}
</a>

link can be resolved to url with out protocol. For example "www.example.com".

3 Answers 3

4

You can just add // to the front of the URL without http(s)

<a href="//{{ link }}"
rel="noopener noreferrer"
target="_blank">
    {{ link }}
</a>
Sign up to request clarification or add additional context in comments.

1 Comment

I found this answer funny. I don't know why, but the question was silly and then this perfectly answers it.
1

You can just use the href without specifying the protocol and make sure not to provide a relative url: So your {{link}} won't contain http or https, just the // Use :

<a href="{{ link }}"
rel="noopener noreferrer"
target="_blank">
    {{ link }}
</a>

Ex: <a href="//www.example.com">Example</a>

Comments

0

If you don't know will your href contain http(s) or not you can use this pipe for transforming it

@Pipe({
    name: 'externalHref'
})
export class ExternalHrefPipe implements PipeTransform {

    transform(href: string): string {
        return /^https?/.test(href) ? href : `//${href}`;
    }
}

And on in the html:

<a  
   [attr.href]="href | externalHref" 
   target="_blank">
     Visit Website
</a>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.