have the url for an external link come from a variable angular

1.1k Views Asked by At

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?

2

There are 2 best solutions below

2
Arunkumar Ramasamy On

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
Peter Weeks On

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