16

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!

danday74
  • 52,471
  • 49
  • 232
  • 283
Zorthgo
  • 2,857
  • 6
  • 25
  • 37

1 Answers1

13

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.

Kols
  • 3,641
  • 2
  • 34
  • 42
punov
  • 798
  • 7
  • 16
  • Hey Punov, Thanks a million for the help and the link! ;) – Zorthgo Oct 24 '15 at 21:06
  • Oh, I made a little mistake, fixed. – punov Oct 26 '15 at 20:31
  • 6
    This only works for navigating within the app itself. You can't use this to route to a completely external URL like `http://www.cnn.com` for example. – Michael Oryl Dec 17 '15 at 15:34
  • 8
    @MichaelOryl is case of the need is to navigate to an external url, you can simply use `window.location.href='http://www.cnn.com'`. Otherwise just follow the answer. – MacKentoch Mar 28 '16 at 08:57
  • 6
    Thats just horribly untestable @MacKentoch –  Feb 21 '17 at 11:51
  • official documentation link broken – Daniele Mar 21 '17 at 15:56
  • `window.location.href = ...` (for non-angular URLs) equivalent for angular is `location.go()` function: https://angular.io/api/common/Location#go – Andriy May 27 '20 at 07:05
  • 1
    please note that `location.go()` does not redirect the page, only changes is history API state. If you need to redirect, you can `inject` document (`import { DOCUMENT } from '@angular/common';`) into your constructor (`@Inject(DOCUMENT) private document: Document`) and use `this.document.location.href = ...` – Andriy May 30 '20 at 21:23