I am trying to implement ion search bar in the following way
My HTML page is
<ion-searchbar (ionInput)="getFilteredItems($event)"></ion-searchbar>
<button ion-item *ngFor="let patient of surveyPatients | async" (click)="showPatientData(patient)">{{patient.name}} - {{patient.age}} - {{patient.idCardNumber}}</button>
Corresponding ts file,
surveyPatients:any;
getFilteredItems(ev: any) {
this.initializeSurveyPatients();
let val = ev.target.value;
alert(val);
console.log(this.surveyPatients.length);
if (val && val.trim() != '') {
this.surveyPatients = this.surveyPatients.filter((item) => {
//alert(item.name);
return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}
initializeSurveyPatients() {
this.surveyPatients = this.afoDatabase.list('/SurveyPatients',
{
query:{
orderByChild: 'district',
equalTo: 'Nalgonda '
}
}
);
}
When I see alert(val) I am getting the what ever the input that is entered in the search box. But when I try console.log(this.surveyPatients.length); I am getting undefined. That is the reason why I am getting Cannot read property 'toLowerCase' of undefined Error.
In the constructor I am running this.initializeSurveyPatients(); Hence I am able to see the data in the front end on page load.
Why I am not able to read the collection this.surveyPatients inside the getFilteredItems method?
Updated Code
initializeSurveyPatients() {
this.afoDatabase.list('/SurveyPatients',
{
query:{
orderByChild: 'district',
equalTo: 'Nalgonda '
}
}
).subscribe(snap => {
this.surveyPatients = snap;
});
getFilteredItems(ev: any) {
//this.initializeItems();
this.initializeSurveyPatients();
let val = ev.target.value;
console.log(this.surveyPatients.length);
if (val && val.trim() != '' ) {
this.surveyPatients = this.surveyPatients.filter((item) => {
return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
console.log(this.surveyPatients.length);
}
}
}
Corresponding html code
<button ion-item *ngFor="let patient of surveyPatients" (click)="showPatientData(patient)">{{patient.name}} - {{patient.age}}
- {{patient.idCardNumber}}</button>
Note: I removed async filter
In this case, I am able to get correct values for console.log(this.surveyPatients.length); before filter and after filter as expected, inside getFilteredItems method. Which confirms us the filter is working.
The only issue is values In the UI are not updating after the filter.