Angular 10 Firebase AutoComplete Search example with AngularFire2 v4

Angular 10 Firebase AutoComplete Search example with AngularFire2 v4

In this tutorial, we’re gonna create a simple Angular 10 App that supports autocomplete search from Firebase Realtime Database using AngularFire2.

Related Posts:
How to integrate Firebase with Angular 10
Angular 10 Firebase CRUD operations with AngularFire2 v4
Angular 10 Firebase Pagination example with AngularFire2 v4
Angular 10 Firebase Filter Data example with AngularFire2 v4

I. Technology

– Angular 10
– AngularFire2 4.0

II. Overview

Assume that we have Firebase Database like this:
angular-4-firebase-pagination-db

We will build an Angular 10 App that supports searching Customer by name:
angular-4-firebase-search-overview

II. How to do

1. Set up the Firebase Project & Install AngularFire2

Please visit this post to know step by step.

angular-4-firebase-integration-copy-firebase-project-config

2. Build Angular 10 App that can add & display list of data items

(Or you can skip this if you just wanna know way to implement searching)
This tutorial bases on code from previous posts (that helps us add and display data).

You can find how to do this in the post:
Angular 10 Firebase CRUD operations with AngularFire2 v4

And more practice with Pagination:
Angular 10 Firebase Pagination example with AngularFire2 v4

angular-4-firebase-crud-goal

We just need to add a Search Component.

3. Support Searching

3.1 Indexing

We usually need to sort data when our database grows larger. It can be done simply by telling Firebase use an index with .indexOn (Firebase Console – Database RULES tab):
angular-4-firebase-search-rules

3.2 Service with AngularFireDatabase

Basing on the code from previous post, we just add a function that returns a List of Items:


import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';

@Injectable()
export class CustomerService {

  private dbPath: string = '/customers';

  constructor(private db: AngularFireDatabase) {}

  findCustomers(start, end): FirebaseListObservable {
    return this.db.list(this.dbPath, {
      query: {
        orderByChild: 'name',
        limitToFirst: 6,
        startAt: start,
        endAt: end
      }
    });
  }
}

3.3 Component for searching

<h2>Find Customers By Name</h2>
<input type="text" (keyup)="search($event)" placeholder="enter name" class="input">

<ul>
	<li *ngFor="let customer of customers">
		<h4>{{customer.name}} - Age: {{customer.age}} - Active:	{{customer.active}}</h4>
	</li>
</ul>

<hr />
<div *ngIf="customers?.length < 1">
	<p>Not found!</p>
</div>

search function will be called on every keyup event that sends current value of the input. This is used for updating startWith and endWith Firebase query pattern.


import {Component, OnInit} from '@angular/core';
import {CustomerService} from '../customer.service';
import { Subject } from 'rxjs/Subject'

@Component({
  selector: 'app-search-customers',
  templateUrl: './search-customers.component.html',
  styleUrls: ['./search-customers.component.css']
})

export class SearchCustomersComponent implements OnInit {

  startWith = new Subject()
  endWith = new Subject()
  customers: any[]
  
  constructor(private customerService: CustomerService) {}

  ngOnInit() {
    this.customerService.findCustomers(this.startWith, this.endWith)
                        .subscribe(customers => this.customers = customers)
  }
  
  search($event) {
      const queryText = $event.target.value
      this.startWith.next(queryText)
      this.endWith.next(queryText + '\uf8ff')
  }

}

endWith gets an added Private Usage Area [PUA] unicode character ‘\uf8ff‘. It is after most regular characters in Unicode, so the query matches all values that start with queryText.

III. Check Result

angular-4-firebase-search-result

IV. Source Code

Angular4Firebase-Search



By grokonez | March 25, 2021.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*