Angular 2 click redirection

How to create a simple redirect when you click on a button in Angular 2? Already tried:

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']); } } 
+13
javascript redirect angular
source share
6 answers

You can use Angular2 event support:

 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']); } } 
+26
source share

I would make it more dynamic using method parameters

Import Angular Router

 import { Router } from '@angular/router'; 

Create button with click event

 <div (click)="redirect(my-page)">My page</div> 

Create a method with the pagename parameter

 redirect(pagename: string) { this.router.navigate(['/'+pagename]); } 

When clicked, the router should go to the correct page

+12
source share

I would say I use the routerLink directive and put this over the a (anchor) tag

 <a [routerLink]="['./SomewhereElse']">Redirect</a> 

You also need to remove ROUTER_PROVIDERS from providers and include it in the bootstrap dependency, and then add ROUTER_DIRECTIVES in the component option directive to use the routerLink directive for HTML. Make sure the RouterModule with its route has been entered into the main application module.

+11
source share

Try routerLink button label routerLink

  <button type="button" [routerLink]="['/edit']">Edit</button> 

More information

+7
source share
 window.location.reload(); 

doing the trick

0
source share

directly in your HTML file is this code.

 <button (click)="btnClick()">Cancel</button> 

in your component.ts file right this code.

 constructor(private router:Router) { } btnClick(){ this.router.navigateByUrl("/payment"); } 
0
source share

All Articles