How to create a link to external URL in Angular 2

痴心易碎 提交于 2020-07-18 03:45:29

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/36082785/how-to-create-a-link-to-external-url-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!