Angular 5 – Instant search with Firestore

Hi Friends,

Hope you are all well. This is one of the most requested posts on this site. In this post let’s see how to build a simple instant search functionality  by querying firestore with the help of rxjs.

Let’s begin.

A screencast of this post:

The code for this post is available here.

First let’s scaffold out an angular app using the cli. Install firebase and angularfire2 using the below command.

Now open up environments directory and in the environment.ts file add the firebase config code. Your environment.ts file should look like below.

Now open up app.module.ts file and add the below code.

It’s pretty much easy to understand, I have just added imports to whatever I installed (firebase and angularfire2).

Now that it’s done, let’s go ahead and build the instant search itself.

I will just make a text field. When the user inputs some text in this field, he/she will be shown a list of results (queried from firestore). Instant Search duh !

Now open up app.component.html and add the below code.

Before proceeding any further, I have created a simple collection with five documents as shown below.


Now open up app.component.ts and add the below code.

Whoa ! that’s a lot of code..

Let’s break it down.

On Initialization, I am simply getting all the clubs (To display when the app loads).

I have created a couple of RxJS subjects through which I can pass the typed values as a stream continuously. I have also created a couple of observables using which I am passing the values to firequery() function.

Note that I am simply writing the querying function here as well, whereas in your apps this would probably written inside a service.

Also another thing to notice is that the startAt() and endAt() parameters in the query are the ones which help us to retrieve the documents starting with our specified string pattern. These two parameters must hold values that are of the same type of the orderBy() argument.

For eg., in this case I have ordered by club which means that the startAt() and endAt() should contain arguments of string type and not numbers or any other custom data types.

Now as you see in the html file, I am simply iterating through the results and displaying them on the front-end. Angular’s 2-way data binding itself helps us in this case, making it look instant on the screen.

That’s it. Hope this helped you guys. If you found this helpful, kindly share it with someone and help them too.

Donate to keep this site alive – click here

Thanks for reading. Peace.. :)

Liked it? Take a second to support admin on Patreon!
  • Manoj Goel

    Hello I used your example with Firestore and wanted to filter data and reload the new data but can’t figure out how to do that with a cdk collection data source

  • Ali Programmer

    What’s the use of searchterm variable?