2

I searched the net to get an example of angular2 router that changes browser urls. All examples that are there doesn't change browser urls when we change different routes. Can you give me a small example in ES6 to demonstrate this?

3 Answers 3

2

An example.

On a Component class:

@RouteConfig([
  { path: '/',          name: 'home',      component: Home },
  { path: '/dashboard', name: 'dashboard', component: Dashboard },
  { path: '/todo',      name: 'todo',      component: Todo }
])
export class App {}

name is not necessary, but can be used to provide an alias.

In the template:

<a router-link="home">Home</a>

Note that router-link must exist on an <a> tag.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much for the answer . Is their a way i can do dynamic routing . Navigate to a route after checking a condition ? Do you have any examples that does dynamic routing with latest version of angularjs 2.0 (..alpha.27) ?
Is it possible to trigger routing from javascript. like $state.go() in angularJS. I 've tried location.go in angular 2 but not working.
FYI, the link to the example is dead.
@shmck can we provide path,as,component and router-link dynamically (as angular variable) ? if yes then how ?
2

After digging into Angular2 source code, I figured out one way to get dynamic routing to work. Let's see this example:

import {Router} from 'angular2/router';
@Component({
    ...
})
export class SampleComponent {
    public router: Router;

    constructor(router: Router) {
        this.router = router;
    }

    goTo(uri) {
        this.router.navigateByUrl(uri);
    }
}

2 Comments

Hi Peter, When you change route do you find that It jumps back to the original route? When I change route to dashboard it straight away returns to login view. Any idea why this occurs?
Could you please show some of your code? Maybe there is a bug in your code that makes your route redirect to that route.
0

in your unit test you would do something like ..

spyOn(instance.router, 'navigateByUrl'); // first thing inside it block

expect(instance.router.navigateByUrl).toHaveBeenCalledWith(uri); // near end of it block when you would have expected the navigation to have happened

Comments

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.