Guide on activating the search-icon feature for Ionic 2 searchboxes

Utilizing the Ionic 2 searchbox to search for data within my list has raised a question in my mind. I am wondering how to console.log my data from that searchbox, specifically when I click on the search icon located within the searchbar.

https://i.sstatic.net/biG36.png

Alternatively, is there another method to filter the data, such as using an ion-input for the searchbox and then consoling the data upon clicking the search icon?

This is the TypeScript file I am working with:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  templateUrl: 'home.html',
})

export class HomePage {
private searchQuery: string = '';
private items: string[];
listitme:string= '' ;

constructor(private navCtrl: NavController) {
this.initializeItems();
}

initializeItems() {
this.items = [
'Harvey Burton',
'Barnett Crosby',
'Peck Brock',
'Rachel Robinson',
'Suzette Frazier',
'Bettie Maddox',
'Haley Bates',
'Tania Chandler',
'Woods Nicholson'
]
}

getItems(ev: any) {
this.initializeItems();

let val = ev.target.value;

if (val && val.trim() != '') {
this.items = this.items.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}

setitem(item){
this.listitme = item;
}

}

This is the HTML code structure:

<ion-header>

<ion-navbar>
  <ion-title>search</ion-title>
</ion-navbar>

<ion-toolbar primary >
  <ion-searchbar (ionInput)="getItems($event)"  [(ngModel)]="listitme" ></ion-searchbar>
</ion-toolbar>

</ion-header>


<ion-content padding>

<ion-list>
  <ion-item *ngFor="let item of items">

  <div (click)=setitem(item) >  
    {{ item }}
  </div>

</ion-item>
</ion-list>  

</ion-content>

Answer №1

If you want to customize the search bar component, you can replace it with a custom one that includes a button and an input field. By doing this, you have more control over what happens when the user interacts with the search functionality.

Custom Component Example

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'app/home.page.html'
})
export class HomePage {
private items: string[];

  query: string = "";
  listItem:string= '' ;

  constructor(private navCtrl: NavController) {
    this.initializeItems();
  }

  initializeItems() {
    this.items = [
      'Harvey Burton',
      'Barnett Crosby',
      'Peck Brock',
      'Rachel Robinson',
      'Suzette Frazier',
      'Bettie Maddox',
      'Haley Bates',
      'Tania Chandler',
      'Woods Nicholson'
    ]
  }

  getItems() {
    // You can add your custom logic here
    console.log('The search button has been clicked...');

    this.initializeItems();
    let val = this.query
    if (val && val.trim() != '') {
      this.items = this.items.filter((item) => {
        return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
  }

  setItem(item){
    this.listItem = item;
  }
}

View Markup

<ion-header>
  <ion-toolbar primary>
    <ion-row>
      <ion-col (click)="getItems()" width-10>
        <button ion-button clear icon-only>
          <ion-icon color="dark" name="search"></ion-icon>
        </button>
      </ion-col>
      <ion-col width-90>
        <ion-input [(ngModel)]="query" type="text" placeholder="Search..."></ion-input>
      </ion-col>
    </ion-row>
  </ion-toolbar>
</ion-header>

<ion-content padding>
<ion-list>
  <ion-item *ngFor="let item of items">
    <div (click)=setItem(item)>  
      {{ item }}
    </div>
  </ion-item>
</ion-list>  
</ion-content>

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

The parameter must be of type 'string', but you are attempting to assign a 'Promise<any>'

Starting a React App requires fetching the user's information from localStorage and initiating a socket connection with the server based on the user's id. However, when trying to pass the user's id to the socket function, TypeScript throws ...

The data received from the API mapping resulted in non-existent information

Currently, I am attempting to extract a specific value from the API response by mapping an array. Once I receive the complete response, the data is clearly defined. EmissionByPolluant(url:string):Observable<emissions[]>{ return this._http.get(url) ...

The appearance of the Angular material component is altered once integrated into a new Angular application compared to its presentation in the provided example

After adding the Angular Material component "Toolbar" to my project, I noticed that it does not appear the same as it does in the example provided. Despite using the same styles, the outcome is different. Here is what the example looks like on the project ...

Implementing endless scrolling in Angular 5 using data fetched from a httpClient call

Looking to incorporate infinite scroll using a large JSON dataset in Angular 5. The goal is to display the first 5 entries initially, and as the user scrolls, load the next 5. I came across this library: https://github.com/orizens/ngx-infinite-scroll, but ...

Creating dynamic DOM elements in Angular templates by utilizing variable values as element types

There's a component I'm working with that I want to render either as a div or span dynamically. To achieve this, I've created an input variable called elementType. Now, the challenge is how to properly render it in the template. Here's ...

Transitioning from angular 5 to angular 6 - What to expect in @angular/core

After upgrading my project from angular 5.2.9 to angular 6.0.0-rc.5, everything seemed to be in order except for a few RxJS fixes in the packages path. One helpful resource I used during the upgrade process was this guide. However, I've run into an i ...

Unsynchronized state of affairs in the context of Angular navigation

Within my Angular project, I am currently relying on an asynchronous function called foo(): Promise<boolean>. Depending on the result of this function, I need to decide whether to display component Foo or Bar. Considering my specific need, what woul ...

Force Angular to log the user out abruptly

I am currently utilizing .Net Core Web API on the backend and Angular on the frontend for my project. When a user signs in, I generate a JWT token for authentication purposes. However, I have chosen not to store this token in the database. One issue I&a ...

I desire for it to effortlessly unlock within my matmenu as soon as the webpage loads

Upon opening my page, I want the material menu to automatically open. However, since there is no click action, I am encountering an error stating that "trigger" is undefined. An error occurred: TypeError: Cannot read properties of undefined (reading &apo ...

Can you explain the usage of the syntax in Angular marked with the @ sign, such as @NgModule, @Component, and @Injectable?

Angular utilizes specific syntax for declaring modules, components, and services, as shown in the example below: @Component({ ... }) export class AppComponent However, this syntax is not commonly seen in traditional JavaScript development. It begs the ...

Having trouble with customizing a selected ListItemButton in Material-UI - need some help with

After reviewing the documentation, I discovered a method to override the styling of the selected class by introducing a new class under .MuiSelected. The implementation looks something like this: const customStyles = makeStyles(() => ({ customizedSele ...

Having trouble making the HTML append to a div in JavaScript and attaching a TypeScript function to a (click) event?

My external javascript file includes a function that adds HTML to the siteLayoutComponent.html DIV. Here is an example of the code: function AddNotification(data) { $("#lstNotification").append(' <li id="' + data.id + '"><a ...

What is the potential return type for a List of JSON objects in Angular 2 using TypeScript?

What could be the possible return type of the getFiles() function other than 'any'? Is there a specific return type that can be used? @Injectable() export class NodeService { constructor(private http: Http) {} getFiles() { retu ...

How to Resolve Angular 2 Reactive Forms Problem the Angular Native Approach, not using jQuery

Utilizing Angular 2 Reactive Forms alongside Typescript, my template structure is as follows: <form [formGroup]="form"> <div class="M"> <div class="X"> <!-- I would like to avoid adding (change)="onChanged()" o ...

Single Column Filtering Feature for Table Matrix

I have been searching for examples of how to implement a column filter in a mat table, but so far I haven't found any. I did come across some information about the filterPredicate method, but couldn't figure out exactly how to approach it. What ...

Exploring the concept of converting a data type into an interface using map operations

Recently, I started learning Angular and I've been trying to wrap my head around how mapping from a response to an interface actually works. Let's take a look at the API response I received: [ { "id": 2, "name" : &qu ...

TypeScript - Variable is inferred to have type 'any' in certain locations where its type cannot be accurately determined

I'm attempting to generate an MD5 hash from the content of an uploaded file. I am trying to set a global declaration to be used within functions, but I encounter an error when trying to utilize it: The error message states - Variable 'hasher&apos ...

Utilize JavaScript, jQuery, or Angular to incorporate identifications into <p> elements

I am working with a dynamically generated HTML document that contains several <p> tags with text inside. My goal is to be able to select a specific <p> tag when a user clicks on the text within it. However, I am restricted from adding ids to th ...

What are the steps to create a sliding carousel using ng2-bootstrap?

I've integrated the Angular2 Bootstrap carousel component from the following link: here, but I'm facing an issue with the transition and animation effects when sliding between items. Any suggestions on how to resolve this? ...

Error NG8002: Unable to associate with 'style' as it is not a recognized attribute of 'ngx-skeleton-loader'

We recently integrated the package "ngx-skeleton-loader" version 8.0.0 into our Angular v15 application. However, we are unable to upgrade to the latest version of the package due to the requirement of updating Angular to v17. According to the documentati ...