1

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?

1

2 Answers 2

4

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})
]);
Sign up to request clarification or add additional context in comments.

Comments

3

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
]);

3 Comments

came here looking for how to setup hashbang routes and found this, even though it was not part of the question - thanks :)
And as per @shmck's helpful answer here routerInjectables was changed to ROUTER_PROVIDERS
To those who are at the very beginning of their journey to the fabulous world of Angular 2: order does matter - ROUTER_PROVIDERS should go before LocationStrategy. Otherwise it wont work. (spent an hour figuring this out)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.