How to create a link to external URL in Angular 2

Ondra Žižka picture Ondra Žižka · Mar 18, 2016 · Viewed 76.9k times · Source

I am new to Angular. I am starting with ver. 2.
I need to link to a file://... URL. I tried normal href:

Note: app is a model object of the web which deals with applications.

<a target="_blank" href="file://{{app.outputPath}}/index.html">no link here</a>.

That doesn't work - the link is there, with correct URL, but Angular seems to block the event somehow. Why?

So I've seen ng-href but that's for Angular 1.x. And there's no *ngHref from what I can tell. So this was just a naive try:

<a target="_blank" *ngHref="file://{{app.outputPath}}/index.html">over a directive</a>.

Also I have seen something with routing but that appears to be intended only for internal links within the application:

<a [router-link]="['/staticReport', {path: app.outputPath}]">see the report</a>.

app.component.ts:

@RouteConfig([
    ...
    {path:"/staticReport/:path", redirectTo: 'file://  ???? ' }
])

What's the way to create an external link?

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Mar 18, 2016

I assume app is assigned async. You can work around this using the Elvis operator:

<a target="_blank" href="file://{{app?.outputPath}}/index.html">no link here</a>.

to not break the binding when Angular tries to resolve it before app actually has a value.

Original This worked for example:

@Component({
  selector: 'my-app',
  template: `
  <h2>Hello {{name}}</h2>
  <a target="_blank" [href]="'file://' + outputPath + '/index.html'">no link here</a>
`
})
export class App {
  outputPath:string = 'www.google.com';

  constructor() {
    this.name = 'Angular2';
  }  
}

Plunker

Actually, your first example works fine as well

<a target="_blank" href="file://{{outputPath}}/index.html">no link here</a>

Plunker