如何在Angular 2中创建指向外部URL的链接

Ond*_*žka 11 external hyperlink angular2-directives angular2-routing angular

我是Angular的新手.我开始用ver.2.
我需要链接到一个file://...URL.我试过正常href:

注意: app是处理应用程序的Web的模型对象.

<a target="_blank" href="file://{{app.outputPath}}/index.html">no link here</a>.
Run Code Online (Sandbox Code Playgroud)

这不起作用 - 链接在那里,具有正确的URL,但Angular似乎以某种方式阻止事件.为什么?

所以我见过ng-href但是那是Angular 1.x. 而且我所知道的并非*ngHref如此.所以这只是一个天真的尝试:

<a target="_blank" *ngHref="file://{{app.outputPath}}/index.html">over a directive</a>.
Run Code Online (Sandbox Code Playgroud)

此外,我看到了一些路由,但似乎只适用于应用程序中的内部链接:

<a [router-link]="['/staticReport', {path: app.outputPath}]">see the report</a>.
Run Code Online (Sandbox Code Playgroud)

app.component.ts:

@RouteConfig([
    ...
    {path:"/staticReport/:path", redirectTo: 'file://  ???? ' }
])
Run Code Online (Sandbox Code Playgroud)

创建外部链接的方法是什么?

Gün*_*uer 15

我假设app被指定为异步.您可以使用Elvis运算符解决此问题:

<a target="_blank" href="file://{{app?.outputPath}}/index.html">no link here</a>.
Run Code Online (Sandbox Code Playgroud)

当Angular在app实际拥有值之前尝试解析它时,不要破坏绑定.

原作 例如:

@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';
  }  
}
Run Code Online (Sandbox Code Playgroud)

Plunker

实际上,你的第一个例子也可以正常工作

<a target="_blank" href="file://{{outputPath}}/index.html">no link here</a>
Run Code Online (Sandbox Code Playgroud)

Plunker