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

Utilizing Kendo Grid for client-side data paging

I am looking to utilize an MVC helper for constructing a grid on the server side, with the ability to dynamically add and remove rows on the client side. To achieve this functionality, I have implemented the following wrapper: @(Html.Kendo().Grid<SIGE ...

Invoking a JavaScript function within a different JavaScript function

Is there a way to ensure that the JavaScript function works properly even when using a text editor? var editor = $('#CKEditor1').ckeditorGet(); editor.on("instanceReady", function () { this.document.on("keydown", function (event) { ...

Convert string to integer value

Is it possible to convert a literal string type (not runtime value) to its corresponding numerical type, for example '1' to 1? I am looking to restrict a variable to only being a key of an object (assuming the type of obj is precise since TypeSc ...

Achievement with ajax: If the status code is 200, execute one function; otherwise, execute a

I can't figure out why this isn't working... I'm using $.ajax to run file.php and pass a POST value from an input field. Even though the file.php is functioning properly (it successfully adds a user to my newsletter), my ajax function seems ...

Organizing a series of objects into groups of four for processing

I have a task of organizing an array of objects that represent game players by assigning each player to a group number based on their current group value. The challenge is to ensure that each group has as close to four players as possible, while also acco ...

Examining the scroll-down feature button

I'm currently experimenting with a scroll down button on my website and I'm perplexed as to why it's not functioning properly. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" c ...

Effortlessly Display or Conceal Numerous Table Columns Using jQuery

I have a small table where I want to hide certain details with a basic button... for instance, table { border-collapse: collapse; } th, td { border: 1px solid gray; padding: 5px 10px; } <button>Show/Hide Details</button> <table> ...

Troubleshooting why content set to a <div> element with JavaScript / jQuery is not persisting after a

This is the current code snippet I am working with: <asp:Button ID="btnSave" runat="server" OnClick="Save" CssClass="StylizedButton" resourcekey="btnSave" /> <div id="lbltot"></div> Below is the JavaScript portion of the code: $(do ...

Troubleshooting problem in Java related to encoding with XMLHttpRequest

Currently, I am utilizing XMLHttpRequest for an ajax call to my server. Let's consider the call: http = new XMLHTTPRequest(); var url = "http://app:8080/search.action?value=ñ" http.open("GET",url,true); http.setRequestHeader("Content-type", "applica ...

What causes variations in the output of getClientRects() for identical code snippets?

Here is the code snippet provided. If you click on "Run code snippet" button, you will see the output: 1 - p.getClientRects().length 2 - span.getClientRects().length However, if you expand the snippet first and then run it, you will notice a slight dif ...

Pair each element with an array of objects and add them to a fresh array

Let's consider an array of objects like, const attachmentData = [{name: 'Suman Baidh',attachment: ["123","456"]}, {name: 'John Sigma',attachment: ["789","101112]}, ...

Is there a way to retrieve the BrowserRouter history from outside of the BrowserRouter component?

Here is a simplified code snippet (using react-router-v5). I am trying to figure out how to access BrowserRouter's history in the logout_Handler() function, even though I am "outside" BrowserRouter. I came across this answer on How to access history ...

Use ajax to load the script

Encountering a puzzling issue with a script loading function on my IIS local web server. function loadJs(scriptName) { var name = scriptName.toString(); var myUrl = 'http://192.168.1.149/7.0.9.5/m/js/'; myUrl += name; debugger; ...

What is the best way to combine the existing array data with the previous array data in JavaScript?

I am implementing server-side pagination in my MERN project. Let's say I retrieve 100 products from the database and want to display only 30 products, with 10 products per page. When a user navigates to the 4th page, I need to make another API call to ...

Shifting the div with a sliding animation!

My webpage features a video background with text overlay, and I am looking to add a button in the center of the page. When users click on this button, I want the current text div to slide up using a CSS transition, revealing another div with the same effec ...

What are the distinctions in type-narrowing when assigning values using ternary expressions versus if-else statements?

It seems that the type checker is handling the typing of m in print() differently based on whether m was assigned through a ternary expression or an if-else statement. What sets apart the first line in the print() function from the commented code below it? ...

The issue of flickering while scrolling occurs when transitioning to a new page in Angular

I have encountered an unusual issue in my Angular 13 + Bootstrap 5 application. When accessing a scrollable page on small screen devices, the scrolling function does not work properly and causes the page to flicker. I observed that this problem does not o ...

Is there a way to reset the yAxes count of a chart.js chart in Angular when changing tabs?

I am currently using chart.js within an Angular framework to visually display data. Is there any method available to reset the y-axis data when changing tabs? Take a look at this Stackblitz demo for reference. Upon initial loading of the page, the data ...

The jQuery hide and show functions lack precision and are too indiscriminate, requiring a more targeted approach

I am designing a unique contact card that captures a user's name and description from an <input> field and appends the input information into a <div> element. This is the flow I am aiming for... User inputs their first and last name alo ...

Users are reporting that verification emails are not being sent when the Accounts.createUser function is used within

I have a simple meteor method set up to create user accounts. In my server/methods.js file: Meteor.methods({ createUserAccount: function(user) { return Accounts.createUser(user); } }); Then in my server/init.js file: Meteor.startup(function() ...