How to get value from searchbox?

I’m using Angular 8/Algolia 3.35.1.

I want to get the value of the searchbox field - what I’ve typed in - before leaving the search page. I found an example at:

but the input value is null at const input = document.querySelector('#searchBox');
Is the #searchBox ID correct, or was that just an example?

When using the browser debugger, and inspecting input.ais-SearchBox-input I’m seeing an empty id, where I’d expect to see #searchBox.

I’m in the ngOnDestroy() function when trying to get the input value, because I want the value before I leave the search page.


Hi @engineering,

You’re right it’s just an example. This code assumes that the #searchBox element already exists on the page. You can use a similar name or adapt the selector name.

You’ve mentioned Angular but the link to the documentation was pointing to InstantSearch for Vanilla JavaScript. Are you aware that we have a version of InstantSearch specifically designed for Angular? It’s called Angular InstantSearch, it should ease the Algolia integration in an Angular application. You can find more information about that in the documentation.

Hope that helps!

Hi Samuel,

Yeah, I’ve studied the Angular docs quite a bit. I actually have a well working component.html, and component.ts. The thing I’m trying to add now is the ability to restore the value to my search box field that it had when I clicked a link in the search results, taking me to another page when I click the Back button. I can do this if I can get the search box’s value. I can’t figure out how to name the search box. My search box code is this:

  <ais-search-box placeholder="Let's find something on TMD...">

I’ve tried adding name=“sb1”, and id=“sb1” to the widget, but that’s not working. How to do this?


If I understood correctly your requirement you would like to sync the state of the search in the URL right? In that case, when a user hits the back button the search state will be where the user left it. InstantSearch (and Angular InstantSearch) supports this feature out-of-the-box. You can find more information about that in the documentation.

Hope that helps!