How can one navigate to a different URL within Angular 2? I know that we can use JavaScript's
window.location.href = '...';
But that seems wrong and would cause a page refresh. I am pretty sure that there should be functionality in Angular 2 that will allow you to move between URLs without refreshing the page. I just can't seem to find it in the documentation.
Thanks in advance!
According to the documentation, you can use Router and its navigate function to change current state, and also pass the parameters, if neccessary:
import {Component, ...} from 'angular2/angular2';
import {Router, ...} from 'angular2/router';
import {HomeCmp} from '../home/home';
@Component({
selector: 'app',
// params of your component here
})
@RouteConfig([
{ path: '/', component: HomeCmp, as: 'MyHome' },
// your other states here
])
export class AppCmp {
router: Router;
constructor(router: Router) {
this.router = router;
}
navigateToHome() {
// for example, that's how we can navigate to our home route
this.router.navigate(['./MyHome', {param: 3}]);
}
}
Here is the link to the official documentation.
And here is a link to seed project with a great example of using Router.