I have integrated the ion-searchbar in my application to filter a list of customers based on their first name and/or last name. However, I am facing two major challenges:
Challenge 1: The search bar currently only matches either the first name OR the last name of a customer, but not both simultaneously. For instance, if a customer's name is Marshall Legend and I type in Marshall
, the filter works fine. Similarly, typing in Legend
also yields results. But when I enter Marshall Legend
, no matches are found.
Challenge 2: Let me explain this with an example scenario. Initially, the search feature works correctly by displaying only customers with the name "Marshall" when searched for. However, as soon as a new customer from another client is added to the list, all customers are displayed regardless of the filter, even though "Marshall" is still present in the search bar.
I have been struggling with these issues for quite some time now and any assistance would be highly appreciated. Below is a snippet of my code:
My component code
export class Tab2Page implements OnInit {
public searchTerm: string = "";
public customerCollection: AngularFirestoreCollection<any>;
public customers: any[];
public unfilteredCustomers: any[];
constructor(private afs: AngularFirestore,
public modalController: ModalController,
private databaseService: DatabaseService) {}
ngOnInit(){
this.customerCollection = this.afs.collection('Customers');
this.customerCollection.valueChanges().subscribe( val => {
this.customers = val;
this.unfilteredCustomers = val;
});
}
/**
* Search functionality
*/
public onSearchTerm() {
if(/\S/.test(this.searchTerm)){
this.customers = this.unfilteredCustomers.filter(customer => {
return customer.lastName.toLowerCase().includes(this.searchTerm.toLowerCase())
|| customer.firstName.toLowerCase().includes(this.searchTerm.toLowerCase());
});
} else {
this.customers = this.unfilteredCustomers;
}
}
My template code
<ion-item-sliding *ngFor="let customer of customers">
<ion-item-options side="start">
<ion-item-option (click)="viewCustomerDetails(customer)">Details</ion-item-option>
</ion-item-options>
<ion-item>
<ion-label>
<ion-icon name="person"></ion-icon> {{customer?.firstName}}
{{customer?.lastName}}
</ion-label>
</ion-item>
<ion-item-options side="end">
<ion-item-option color="danger" (click)="removeCustomer(customer)">Return</ion-item-option>
</ion-item-options>
</ion-item-sliding>