Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2's equivalent to window.location.href?

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!

like image 202
Zorthgo Avatar asked Oct 24 '15 20:10

Zorthgo


People also ask

What is window location HREF in angular?

The window. location. href property returns the URL of the current page.

Is window location href a string?

window. location. href is the same as the toString method of window. location , so you can choose to use either variable when using comparing as a string.

How do you pass data using Windows location href?

What you have to do is to set up a form tag with data fields in it, set the action attribute of the form to the URL and the method attribute to POST, then call the submit method on the form tag.

What is window top location href?

top. location. href ) returns the location of the topmost window in the window hierarchy. If a window has no parent, top is a reference to itself (in other words, window === window. top ).


1 Answers

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.

like image 77
punov Avatar answered Oct 21 '22 11:10

punov