ThreeAccents ThreeAccents - 5 months ago 23
AngularJS Question

Redirect within component Angular 2

I have a simple method that at the end of it I want to redirect to another component:

export class AddDisplay{
display: any;

addPairTo(name: string, pairTo: string){
this.display = {};
this.display.name = name;
this.display.pairTo = pairTo;

}
}


What I wanna do is at the end of the method redirect to another component:

export class AddDisplay{
display: any;

addPairTo(name: string, pairTo: string){
this.display = {};
this.display.name = name;
this.display.pairTo = pairTo;

this.redirectTo('foo');
}
}


How do I achieve this in Angular 2?

kit kit
Answer

first configure routing

import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router';

and

@RouteConfig([
  { path: '/addDisplay', component: AddDisplay, as: 'addDisplay' },
  { path: '/<secondComponent>', component: '<secondComponentName>', as: 'secondComponentAs' },
])

then in your component import and then inject Router

import {Router} from 'angular2/router'

export class AddDisplay {
  constructor(private router: Router)
}

the last thing you have to do is to call

this.router.navigateByUrl('<pathDefinedInRouteConfig>');

or

this.router.navigate(['<aliasInRouteConfig>']);