Change route params without reloading in Angular 2 Change route params without reloading in Angular 2 angular angular

Change route params without reloading in Angular 2


As of RC6 you can do the following to change URL without change state and thereby keeping your route history

    import {OnInit} from '@angular/core';    import {Location} from '@angular/common';     // If you dont import this angular will import the wrong "Location"    @Component({        selector: 'example-component',        templateUrl: 'xxx.html'    })    export class ExampleComponent implements OnInit {                constructor( private location: Location )        {}        ngOnInit() {                this.location.replaceState("/some/newstate/");        }    }


You could use location.go(url) which will basically change your url, without change in route of application.

NOTE this could cause other effect like redirect to child route from the current route.

Related question which describes location.go will not intimate to Router to happen changes.


Using location.go(url) is the way to go, but instead of hardcoding the url , consider generating it using router.createUrlTree().

Given that you want to do the following router call: this.router.navigate([{param: 1}], {relativeTo: this.activatedRoute}) but without reloading the component, it can be rewritten as:

const url = this.router.createUrlTree([], {relativeTo: this.activatedRoute, queryParams: {param: 1}}).toString() this.location.go(url);