Efficiently search and filter items across multiple tabs using a single search bar in the Ionic 2

I am currently working on implementing a single search bar that can filter lists in 2 different tabs within Ionic 2. The search bar is functional, and I have a method for filtering through objects. However, my goal is to allow users to select different tabs to specify what they want to search for. For instance, the "Search Page" includes an ion-searchbar and ion-tabs with 2 options - People and Blogs. When a user inputs content into the search bar, it should filter results based on the active tab. By default, the page displays results for people, but users can click on the blogs tab to switch their search focus. Currently, this is how the SearchPage looks like:

<ion-header text-center>
  <ion-navbar>
    <ion-title>Search Page</ion-title>
  </ion-navbar>
<ion-header>

<ion-searchbar [(ngModel)]="searchTerm" [formControl]="searchControl" (ionInput)="onSearchInput()"></ion-searchbar>
<div *ngIf="searching" class="spinner-container">
  <ion-spinner></ion-spinner>
</div>

<ion-tabs tabsPlacement="top">
  <ion-tab tabIcon="people" [root]="peopleSearch"></ion-tab>
  <ion-tab tabIcon="pricetags" [root]="postsSearch"></ion-tab>
</ion-tabs>

Placing the search bar in the main section ensures that it remains constant while switching between tabs without needing to refresh or redraw. However, I'm facing challenges accessing its value and event listeners on both tab pages. Currently, I can only utilize them on the main page. I'm considering using @ViewChild to address this issue, but I lack the expertise in Ionic to implement it effectively across both tabbed pages. Any guidance would be greatly appreciated. Thank you.

Here's a tutorial where I sourced some of my code: Link

Answer №1

Here are two approaches to achieving the same result, one simple and one more precise.

1) Retrieve data using

navCtrl.parent.getActive().instance.searchTerm

To access the data from the parent tabs, you can utilize the getActive() method which returns the instance of the active view Controller containing the desired information.

this.tabsInstance = navCtrl.parent.getActive().instance;

data | filter: searchTerm

2) Utilize EventEmitters for a cleaner solution with better class separation.

Add an EventEmitter in the tabs class

public searchEmitter: EventEmitter<string> = new EventEmitter<string>();

Attach it to your root params

<ion-tab [rootParams]="searchEmitter" tabIcon="people" [root]="peopleSearch"></ion-tab>
<ion-tab [rootParams]="searchEmitter" tabIcon="pricetags" [root]="postsSearch"></ion-tab>

In each class, retrieve the navParams and assign them to the searchTerm variable.

public searchTerm:string;

constructor(navParams:NavParams){
      if(navParams)
      navParams.data.subscribe(searchTerm => this.searchTerm = searchTerm);
}

Emit changes in the tabs when the searchInput is updated

this.searchEmitter.emit(this.searchTerm);

The second approach may be lengthier, but it is undoubtedly more accurate.

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 Autocomplete field's label remains visible even after the form is submitted

I am currently developing a feature that allows users to select an option in the Autocomplete component. In the parent component, I pass these props: const filterDropdownConfig: FilterSelectAutocomplete = { data: scenariosList, label: { className: &apos ...

Echo a JS variable into PHP and then insert a PHP file into an HTML element - a step-by-step guide!

Greetings to the wonderful community at stackoverflow, I am currently working on a variable code that allows for easy insertion of code from another file, such as a div. I am curious if it is possible to include a PHP file using JavaScript and JS variable ...

Guide on implementing hover effects in React components

Within my component SecondTest, I have defined an object called useStyle which sets the background color to red. Is it feasible to add a hover effect to this object? const useStyle = { backgroundColor: "red", }; function SecondTest() { return < ...

How do I start using Google Analytics: application.js, ga.js, or a beginner’s guide?

Hello there! I was wondering if anyone could provide a comprehensive guide or step-by-step tutorial on setting up Google Analytics with some examples. The information I found so far only covers signing up and obtaining a tracking code, but it doesn't ...

Encountered an error when incorporating nguniversal/express-engine into an Angular project: "Unable to locate the BrowserModule import in /src/app/app.module.ts"

One of the initial questions Purpose The main aim is to integrate SSR into my Angular project using ng add @nguniversal/express-engine --clientProject [name] (to enable dynamic prerendering of meta tags). Expected Outcome I anticipated the command to run ...

Can you guide me on how to access an Angular route using a URL that includes query parameters?

Within my current development project, I have implemented a user profile route that dynamically navigates based on the user's _id. This means that when a user accesses the page, their _id is stored in localStorage and then used to query MongoDB for th ...

Lamenting the Perils of Losing AngularJS Rootscope Data upon Refresh

Currently, I am facing an issue in AngularJS 1.x. When I save a value in the $rootScope and pass to the next page or router, unfortunately, the $rootScope value gets lost upon refreshing the page (F5/Window Reload). I need a solution that doesn't inv ...

Developing a standard jQuery function for adding event listeners

Attempting to replicate the functionality of Google Maps' addListener using jQuery listeners for clicks, keypresses, etc. In Moogle Maps, you can use .event.addListener(map, 'click', function()... or switch 'click' with 'drag ...

Exploring the world of AngularJS: delving into $http requests, navigating

After facing challenges with using CORS and http authentication in AngularJS, I have learned an important lesson that I would like to share. Special thanks to igorzg for providing valuable assistance. The situation is as follows: You need to make a POST re ...

Introducing React JSX via a nifty bookmarklet

Looking to convert code found in an HTML file into a bookmarklet? Here's the code snippets involved: <script src="JSXTransformer-0.13.3.js"></script> <script src="react-0.13.3.js"></script> <script type="text/jsx;harmony=tr ...

What is the best way to retrieve environment variables from an NPM package in an Angular 5 application

Is there a method for my node module, created from an Angular 5 application, to access the environment variable from the Angular 5 application (environments/environment.ts)? Perhaps Angular 5 exports its environment variables to JavaScript global variables ...

Ajax displays JSON data within an array format

Looking for a solution where I have MySQL data displayed in a table, with each row having a button. When the button is clicked, a bootstrap modal should appear containing that data. I have converted the MySQL data to JSON format and assigned the ".view_dat ...

Tips for choosing all elements in a form that have a specific class assigned

I am attempting to target all fields in a form with a specific class name and then select all the remaining fields. This is my form: <form style="margin:20px 0" id="myform_2"> <p> Query Name : <input i ...

Creating a duplicate or copy of an element in jQuery using

My dilemma involves a div that consists of text/images and a custom jQuery plugin designed for those images. The plugin simply executes a fadeIn/fadeOut effect every 3 seconds using setInterval. This particular div acts as a "cache" div. When a user wants ...

Deleting a key from a type in TypeScript using subtraction type

I am looking to create a type in TypeScript called ExcludeCart<T>, which essentially removes a specified key (in this case, cart) from the given type T. For example, if we have ExcludeCart<{foo: number, bar: string, cart: number}>, it should re ...

React - Render an element to display two neighboring <tr> tags

I'm in the process of creating a table where each row is immediately followed by an "expander" row that is initially hidden. The goal is to have clicking on any row toggle the visibility of the next row. To me, it makes sense to consider these row pa ...

Removing custom scrollbars using jQuery from an element

Utilizing mCustomScrollbar with jQuery UI dialog boxes. When attempting to initialize mCsutomScrollbar on $(window).load as instructed, it fails because the dialogs are not yet visible. As a workaround, I've had to initiate mCsutomScrollbar on the op ...

The header() function triggers automatic page redirection instead of waiting for the form to be submitted

When I created a form that automatically sends an email upon submission, my goal was to direct the user to a thank you page after the email is sent. In my search for a solution, I stumbled upon the header() function in php and attempted to use it with the ...

Tips for sending a query using the http GET method in Next.JS 14 API routes

When using the Next.js 14 API route, I am passing a page in the GET method to paginate the data fetched from my database. However, an error is thrown when trying to retrieve the query from the request: Property 'query' does not exist on type &a ...

ACTUAL preventing a component from losing its focus

I have been exploring ways to effectively stop a DOM element from losing focus. While researching, I came across different solutions on StackOverflow such as: StackOverflow solution 1 StackOverflow solution 2 StackOverflow solution 3 However, these sol ...