Change route params without reloading in Angular 2

Marcos Basualdo picture Marcos Basualdo · Feb 25, 2016 · Viewed 130.1k times · Source

I'm making a real estate website using Angular 2, Google Maps, etc. and when a user changes the center of the map I perform a search to the API indicating the current position of the map as well as the radius. The thing is, I want to reflect those values in the url without reloading the entire page. Is that possible? I've found some solutions using AngularJS 1.x but nothing about Angular 2.

Answer

tjuzbumz picture tjuzbumz · Sep 12, 2016

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/");
        }
    }