Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 redirect on click

How to create simple redirect on click on some 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']);
    }

}
like image 463
IntoTheDeep Avatar asked May 16 '16 10:05

IntoTheDeep


2 Answers

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']);
  }
}
like image 76
Thierry Templier Avatar answered Oct 10 '22 09:10

Thierry Templier


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

like image 34
0x1ad2 Avatar answered Oct 10 '22 07:10

0x1ad2