Javascript 单击时 Angular 2 重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37252146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 redirect on click
提问by IntoTheDeep
How to create simple redirect on click on some button in Angular 2? Already tried:
如何在单击 Angular 2 中的某个按钮时创建简单的重定向?已经尝试过:
import {Component, OnInit} from 'angular2/core';
import {Router, ROUTER_PROVIDERS} from 'angular2/router'
@Component({
selector: 'loginForm',
templateUrl: 'login.html',
providers: [ROUTER_PROVIDERS]
})
export class LoginComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.navigate(['./SomewhereElse']);
}
}
回答by Thierry Templier
You could leverage the event support of Angular2:
您可以利用 Angular2 的事件支持:
import {Router} from '@angular/router';
@Component({
selector: 'loginForm',
template: `
<div (click)="redirect()">Redirect</div>
`,
providers: [ROUTER_PROVIDERS]
})
export class LoginComponent implements OnInit {
constructor(private router: Router) { }
redirect() {
this.router.navigate(['./SomewhereElse']);
}
}
回答by 0x1ad2
I would make it more dynamic using method parameters
我会使用方法参数使它更动态
Import the angular router
导入角度路由器
import { Router } from '@angular/router';
Create a button with click event
创建一个带有点击事件的按钮
<div (click)="redirect(my-page)">My page</div>
Create a method with a pagename parameter
创建一个带有 pagename 参数的方法
redirect(pagename: string) {
this.router.navigate(['/'+pagename]);
}
When clicked the router should route to the correct page
单击时,路由器应路由到正确的页面
回答by Pankaj Parkar
I'd say use routerLink
directive & placed that over a
(anchor) tag
我会说使用routerLink
指令并将其放在a
(锚点)标签上
<a [routerLink]="['./SomewhereElse']">Redirect</a>
Also you need to remove Make sure ROUTER_PROVIDERS
from providers
& include it in bootstrap dependency and then add ROUTER_DIRECTIVES
in directives option of component to use routerLink
directive on HTML.RouterModule
with its route has been injected in Main App module.
您还需要确保ROUTER_PROVIDERS
从providers
引导程序依赖项ROUTER_DIRECTIVES
中删除并包含它,然后添加组件的指令选项以routerLink
在 HTML上使用指令。RouterModule
其路由已注入 Main App 模块。
回答by atish shimpi
回答by java1977
window.location.reload();
does the trick
有诀窍
回答by Sanjay Makwana
in your html file right this code.
在您的 html 文件中正确使用此代码。
<button (click)="btnClick()">Cancel</button>
in your component.ts file right this code.
在您的 component.ts 文件中正确使用此代码。
constructor(private router:Router) { }
btnClick(){
this.router.navigateByUrl("/payment");
}