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!
The window. location. href property returns the URL of the current page.
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.
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.
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 ).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With