The Ionic search bar will only initiate a search once the keyboard is no longer in view

In my Ionic application, I have implemented a search bar to filter and search through a list. The filtering process is triggered as soon as I start typing in the search bar. However, the updated results are not displayed on the screen until I manually hide the keyboard by clicking the arrow down button. Let me illustrate this with the following images:

Here is an image of the list before initiating a search: https://i.stack.imgur.com/WIlUw.jpg

Next, here is an image of me attempting to search for "abc". Even though the searching process has already occurred in the background, the updated results are not visible yet (I want the search to happen with every keystroke). https://i.stack.imgur.com/7VYhB.jpg

Only after tapping the arrow down button from the previous image, the filtered/searched results finally appear. https://i.stack.imgur.com/I3GA2.jpg

HTML:

<ion-content padding>

    <ion-list>

        <div *ngFor="let period of periodsClone; let j = index">
            <ion-item-divider>{{ period.month | monthNameFormat }} {{ period.year }}
                <div item-end><b>€{{ period.sum |  number : '1.2-2' }}</b></div>
            </ion-item-divider>
            <div *ngFor="let declaration of period.declarations;let i = index;">
                <button ion-item text-wrap detail-none (click)="openDeclaration(period.number,declaration.id);">

                        <ion-icon item-start style="color: grey;" name="time" *ngIf="declaration.status == '1';"></ion-icon>
                        <ion-icon item-start style="color: red;" name="close" *ngIf="declaration.status == '2';"></ion-icon>
                        <ion-icon item-start style="color: lightgreen;" name="checkmark" *ngIf="declaration.status == '3';"></ion-icon>

                        <h2>{{ declaration.name }}</h2>
                        <p>{{ declaration.date | date:'dd-MM-yyyy' }}</p>
                        <p style="color: red;">{{ declaration.comment }}</p>
                        <div item-end>€ {{ declaration.amount | number : '1.2-2'}}</div>
                    <ion-icon name="arrow-forward" item-end></ion-icon>
                </button>
            </div>
            <br>
            <br>
        </div>

    </ion-list>

</ion-content>


<ion-footer>
    <ion-searchbar [(ngModel)]="searchInput" (ionInput)="search($event)">
    </ion-searchbar>
</ion-footer>

Typescript:

search(ev){
    this.periodsClone = this.periods.map(x => JSON.parse(JSON.stringify(x)));

    let value = ev.target.value.toLowerCase();

    for (let i = 0; i < this.periodsClone.length; i++) { 
      for (let j = 0; j < this.periodsClone[i].declarations.length; j++) { 
        let toRemove = false;
        (this.periodsClone[i].declarations[j].name.toLowerCase().includes(value) || this.periodsClone[i].declarations[j].description.toLowerCase().includes(value) ? toRemove = false : toRemove = true);
        (toRemove ? (this.periodsClone[i].declarations.splice(j,1) , j = 0) : false);
      }
    }

  }

And:

private periods: Period[] = [];
private periodsClone: Period[] = [];
private searchInput: string;

And:

  ionViewWillEnter() {
    this.periods = this.declarationService.getPeriods();
    this.periodsClone = this.declarationService.periodsDuplicate;
  }

How can I ensure that the search functionality triggers immediately upon entering a character in the search field?

PS: This issue is observed on both my Nexus 6 and Huawei P10 devices.

EDIT:

I am still grappling with this problem, and meanwhile, I made some modifications to the search function code:

search(event) {
    this.periodsClone = this.periods.map(x => JSON.parse(JSON.stringify(x)));
    let value = event.target.value.toLowerCase();

    if (value != '') {

      this.periodsClone = this.periodsClone.filter((period) => {
        return (
          period.declarations.filter((declaration) => {
            return (
              declaration.name.toLowerCase().includes(value) ||
              declaration.description.toLowerCase().includes(value)
            )
          }).length > 0
        )

      })
    }

    console.log(this.periodsClone);
  }

Period:

//Entities
import { Declaration } from './declaration.entity';

export class Period {
    constructor(
        public id: number,
        public status: string,
        public year: number,
        public month: number,
        public sum: number,
        public orderNumber: string,
        public userId: string,
        public submitDate: Date,
        public comment: string,
        public declarations: Declaration[]
    ) { }
}

Declaration:

//Entities
import { FileCustom } from './file.entity';
import { Period } from './period.entity';
import { Project } from './project.entity';

export class Declaration {
    constructor(
        public id: number,
        public status: string,
        public name: string,
        public description: string,
        public amount: number,
        public date: Date,
        public period: Period,
        public userId: string,
        public files: FileCustom[],
        public comment: string,
        public project: Project
    ) { }

}

Currently, the challenge lies in reproducing the issue consistently, as it occurs intermittently. I have captured both scenarios:

Working example video

Non-working example video

EDIT 2:

I also attempted using a regular input method like so:

<ion-input (keyup)="search($event)" placeholder="Search" clearInput></ion-input>

However, the same issue persists despite trying this approach.

Answer №1

After seeking help on the Ionic Slack, I was able to identify the root of the issue. It turns out that Angular wasn't always detecting changes in the same way I anticipated. To resolve this, I had two options: either create a new instance of the periods list to trigger detection automatically, or manually force the changes to be detected. I opted for the latter solution:

First, I added this import statement:

import { ChangeDetectorRef } from '@angular/core';

Then, I included this line in the constructor:

private cd: ChangeDetectorRef

Finally, at the end of the search function, I called:

this.cd.detectChanges();

By implementing this approach, I was able to ensure that changes were consistently detected and applied as intended.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to hide the <dd> elements within a <dl> using knockout's custom data binding upon initialization?

I have implemented a <dl> where the <dd> can be expanded/collapsed by clicking on the corresponding <dt> using knockout's data binding. The inspiration for my solution came from a tutorial on creating custom bindings. Currently, I h ...

What could be causing my function to not provide the expected output?

Whenever I try to invoke the function from another part of the code, I encounter an issue where it returns undefined before actually executing the function. The function is stored in a service. login.page.ts: ngOnInit(){ console.log(this.auth.getRole()) ...

"Encountered a Json error with a bizarre character causing the string

After extracting some json data from a website, I encountered an issue when trying to parse it using vscode. I kept getting an 'unexpected end of string' error on the "content" line: Here is the json: { "name": "Anna Vergnas", "date" ...

Angular 7 - Implementing periodic JSON data retrieval from server and maintaining local storage within Angular application

Seeking guidance on how to handle updating a static json file stored in the assets directory in an Angular 7 project. The goal is to periodically fetch a json from a server, check for updates, and perform post-processing on the data in the static file (ess ...

Tips for relocating the indicators of a react-material-ui-carousel

I am working with a carousel and dots indicators, but I want to move the indicators from the bottom to the circular position as shown in the image below. I attempted using a negative margin-top, but the indicators ended up being hidden. Is there another ...

Obtain the maximum or minimum value from an associative array using a function and provided parameters

Here is the code I have so far: <!DOCTYPE html> <html> <body> <button onclick="scanarray('a', 'max')">Test with a, max</button> <button onclick="scanarray('b', 'min')">Test with ...

Retrieve the variable declared within the event

How can I access a variable set in an event? Here is the code snippet: $scope.$on('event_detail', function (event, args) { $scope.id = args; console.log($scope.id); // This prints the correct value }); console.log($scope.id); // ...

Encountering issues while trying to establish a connection to MongoDB through JavaScript

I have developed a code for seamlessly integrating various social networking logins with nodejs. Below is my server.js file: // include the necessary tools var express = require('express'); var app = express(); var port = process.env ...

Tailored NodeJS compilation incorporating JavaScript modules

Can NodeJS be built together with specific JavaScript modules? I am aware that for native modules, node-gyp can assist with this, but I am unsure about how to accomplish this with JavaScript modules. My goal is to use a custom application without needing t ...

Encountering difficulties in JavaScript while trying to instantiate Vue Router

After following the guide, I reached the point where creating a Vue instance was necessary (which seemed to work). However, it also required providing a Vue Router instance into the Vue constructor, as shown below. const router = new VueRouter({ routes }) ...

Tips for utilizing an adaptive design with Angular

I am working on designing a page that allows for scrolling if needed. On each section of the page, I will be incorporating specific components with unique colors to enhance the layout. However, my current HTML code is not producing the desired result as sh ...

Adding arguments to the Gradle Sync in Android Studio

My goal is to send the SVN revision number to our build machine which is based on Gradle. I can easily use variables like $svnRevision in the build.gradle file and run the command "gradlew.bat build -PsvnRevision="1234". However, Android Studio is having ...

Exploring JSON objects within other JSON objects

As I work on my Angular App and implement angular translate for dual language support, I've encountered an issue with accessing nested items within my JSON object. After carefully constructing my JSON and verifying its validity, I attempt to retrieve ...

I need help figuring out the proper way to establish an indexing path in cosmos db using the nodejs sdk

I'm currently facing a challenge with setting up the indexing policy for one of my cosmosdb containers. Within my cosmosdb, I have a container that stores information about user sessions. Using the node sdk, I am defining the containers, partition key ...

What steps should I take to incorporate an Alarm Clock system into my applications?

Can someone guide me on how to incorporate an alarm clock feature into my application? I am looking to create an alarm that functions similar to the system alarm or if there is any Intent available to set a system alarm from my app. ...

Can you please provide a method for determining which characters are adjacent to each other

I am in the process of developing a markdown editor and I require a check to identify if adjacent characters are specific characters, removing them if they match or adding them otherwise. For example, if the selected text is surrounded by two asterisks li ...

Revitalizing task following user's adjustment of location settings

User flow: The user clicks a button and is then redirected to MapActivity, where they can see a Google Maps display. A specific location is provided, along with a button that allows the user to create a route from their current location to the specified on ...

Importing models in SceneJS does not function properly with Internet Explorer

I've been exploring different webGL frameworks lately. While I like SceneJS, I've noticed some compatibility issues with Internet Explorer. For instance, in IE 11, importing OBJ files seems to cause the online examples to freeze up: Check out th ...

Maintain the communication in openfire while displaying the user as inactive in xmpp

Currently working on an android chat application using the openfire smack library. I have implemented a bound service to handle incoming messages when the app is in the background. The service successfully listens for messages, but the issue arises with ...

Ways to retrieve content from a website

After conducting thorough research on this matter, I stumbled upon an answer here. Despite following the provided solution, the process is still not functioning as expected. My goal is simple - to extract text from a webpage like Google and convert it into ...