Angular 2 redirect on click

You could leverage the event support of 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']);
  }
}

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

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

When clicked the router should route to the correct page


I'd say use routerLink directive & placed that over a(anchor) tag

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

Also you need to remove 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. Make sure RouterModule with its route has been injected in Main App module.