How to change router by typescript in angular2?

3.8k Views Asked by At

For example, I use router-link like this:

<li><a [router-link]="['/start']">Start</a></li>

But how can I change the router to /start by typescript?

2

There are 2 best solutions below

3
On

I believe you're asking how to configure your routes in Angular 2.

  • 1) import & load your router
  • 2) Use @RouteConfig to setup your routes on a component

  • Optional: Add a hashbang (#) to your url

Here's an example:

import {Component, View, bind, bootstrap} from 'angular2/angular2';
import {routerInjectables, routerDirectives, Router, RouteConfig} from 'angular2/router';
import {LocationStrategy, Location, HashLocationStrategy } from 'angular2/router'; // options2: HTML5LocationStategy

// Components
import {Home} from 'home';
import {SomewhereElse} from 'somePlace';

@Component({
  selector: 'app-name'
})
@View({
  template: '<router-outlet></router-outlet>',
  directives: [routerDirectives]
})
@RouteConfig([
  {path: '/start', as:  component: Home},
  {path: '/place/:placeId', component: SomewhereElse}
])
class AppName {}

bootstrap(AppName, [
  routerInjectables,
  bind(LocationStrategy).toClass(HashLocationStrategy) // for hashbang routes (/#/)
  // alternative: use HTML5LocationStrategy
]);
0
On

Small update related to hash location strategy.

In recent versions of angular2 the bind method is deprecated so you can change location strategy by using provide method.

bootstrap(MyApp, [
  ROUTER_PROVIDERS,provide(LocationStrategy, {useClass: HashLocationStrategy})
]);