<button type="button" (click)="goToSpecificUrl('http://stackoverflow.com/')">Open URL</button>
<button type="button" (click)="gotoGoogle()">Open Google</button>
<li *ngFor="item of itemList" (click)="goToSpecificUrl(item.link)"> // (click) don't enable pointer when we hover so we should enable it by using css like: **cursor: pointer;**
10 回答
我用了window.location.href ='http://external-url';
对我来说,重定向在Chrome中有效,但在Firefox中不起作用 . 以下代码解决了我的问题:
I you need à target="_blank" ,你可以使用window.open:
在撕掉我的头后,解决方案只是将http://添加到href .
我使用Angular 2 Location做到了,因为我不想自己操纵全局窗口对象 .
https://angular.io/docs/ts/latest/api/common/index/Location-class.html#!#prepareExternalUrl-anchor
它可以这样做:
正如丹尼斯斯莫勒克所说,The solution已经死了 . 将
window.location.href
设置为您要切换到的URL,它就可以正常工作 .例如,如果组件的类文件(控制器)中有此方法:
然后,您可以通过模板中的按钮(或其他)上的相应
(click)
调用来简单地调用它:前面描述的方法的Angular方法是从
@angular/common
(或Angular <4中的@angular/platform-browser
)导入DOCUMENT
并使用在一个函数内部 .
some-page.component.ts
some-page.component.html
查看plateformBrowser repo了解更多信息 .
如果你一直在使用OnDestry生命周期钩子,你可能有兴趣在调用window.location.href =之前使用这样的东西 .
这将触发您可能喜欢的组件中的OnDestry回调 .
哦,还有:
是你找到路由器的地方 .
---编辑---可悲的是,我在上面的例子中可能错了 . 至少它现在没有在我的 生产环境 代码中起作用 - 所以,在我有时间进一步调查之前,我这样解决它(因为我的应用程序确实需要钩子)
基本上路由到任何(虚拟)路由以强制挂钩,然后按要求导航 .
在你的 component.ts
在你的 component.html
在较新版本的Angular中,窗口为
any
你可以使用这个 - >
window.location.href = '...';
这会将页面更改为您想要的任何内容..