0

I have a situation where I want to get some url's from a database via an api and then have those (external) links on my page.

So I want to do something like this:

component.ts

public url: string;

ngOnInit(): void {
  this.url = getFromAPI()
}

component.html

<a href="{{url}}"> here's a link </a>

but for the life of me, I can't figure out how to do it. I've tried to use the attribute directive approach here: https://stackblitz.com/edit/angular-external-links?file=src%2Fapp%2Fexternal-url.directive.ts

But I must be doing it wrong because it's not working for me; my link still comes out as https://localhost:4200/urlFromAPI

I've also tried the approach described here: https://kevinphelps.me/blog/2017-06-30-handling-external-links-in-angular

but then my links don't work at all. Clicking on them does nothing.

Is there an easy way to do this that I'm missing? Or is this actually difficult in Angular?

Peter Weeks
  • 291
  • 2
  • 16
  • Not sure, what you want to achieve, Are you looking for `target="_blank"` or Are you getting `router-links` from API or you want to open link in next page? – Naren Nov 05 '20 at 20:36
  • I want to have a link to an external website from an Angular application, with the value for the href coming from a variable, and not have the Angular router assume that it's supposed to be an internal link.Look at the second link I posted in my question, that's the most recent thing I've tried to implement to get this to work. – Peter Weeks Nov 05 '20 at 20:39

2 Answers2

0

In your stackblitz app, Your set default value as false in you deactivateGuard. So that, the navigation has blocked over there.

Here, I need a confirmation from user whether navigate or not using window.confirm('Are you sure?').

In your routing.module.ts File:

{
   provide: deactivateGuard,
   useValue: () => {
     console.log('Guard function is called!')         
     return window.confirm("Are you sure?");
   }
}

Ref: https://stackblitz.com/edit/angular-external-links-aph8hk?file=src%2Fapp%2Frouting.module.ts

Let me know if it's worked.

0

OK. If the link starts with "http[s]://", angular won't assume it's an internal link. That's all.

Peter Weeks
  • 291
  • 2
  • 16