4

I've got an angular table that has a number of search boxes above the header. As the user types in a search box the relevant column is filtered.

I'd like to write the values in the search boxes directly to the URL, so as the user types and changes the search criteria the parameters in the URL are automatically updated. If the user bookmarks or shares the URL, or navigates from and to it in history the previous search parameters are used.

I've looked at the router docs but the only way I saw to write to the URL was to navigate to it. I don't want routing, guards and navigation events to be firing just a more direct binding between the search form and URL parameters.

I'm using Angular 6.1.3. Can I do this within angular or do I need to go to go behind the scenes and try and bypass it?

I think using RouteReuseStrategy would save some rendering time if I was navigating but I'm not sure it would be enough.

Stephen Turner
  • 7,125
  • 4
  • 51
  • 68

1 Answers1

1

You're looking for Location#replaceState (emphasis mine):

Changes the browsers URL to the normalized version of the given URL, and replaces the top item on the platform's history stack.

Just call this function whenever there's a change:

ngOnInit () {
  this.form.get('field').changes.subscribe(value => {
    this.location.replaceState('search/' + value)
  })
}
Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91