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

"Process the contents of a file by reading it line by line in a

Currently, I am reviewing the documentation for the nodejs readline module in order to tackle a task that involves reading a very large file line by line. The solution using readline seems promising, although I require it to read lines synchronously - mean ...

Attempting to save the result of a fetch call into a variable for the purpose of rendering it as a list in a

I'm attempting to fetch the top 5 NFT collections based on volume and display them in a table format. However, I'm facing an issue where the data is not being mapped correctly and when I click the "get" button, all content on the webpage disappea ...

Tooltipster fails to function with elements that are dynamically created

I've been struggling with this issue for several days now, but I can't seem to find a solution. In my JavaScript code, I have a function that generates HTML after an Ajax call is completed. I call this function in the following manner: $(documen ...

Retrieve the HTML value of an element in Vue.js by clicking on its adjacent element

Hey there, I'm currently working on a simple notes app and I've hit a roadblock with one particular feature. In my project, I have a card element with a delete button as a child. What I need to achieve is to check if the value of the .card-title ...

Angular: The Ultimate Guide to Reloading a Specific Section of HTML (Form/Div/Table)

On my create operation page, I have a form with two fields. When I reload the page using window.reload in code, I can see updates in the form. However, I want to trigger a refresh on the form by clicking a button. I need help writing a function that can r ...

Can you explain the use of the 'this' keyword in map() and call() functions?

Recently, I've been revisiting my understanding of how to use call() and map() with a NodeList in JavaScript. It was quite easy to find information on how call() works, and there are plenty of examples of how it can be used with map(). However, whil ...

Using JavaScript's regular expressions to identify a code block that commences with a specified pattern

Currently, I am working on a JavaScript script and I am in need of a Regex pattern to quickly match "JSDocs". The specific pattern that I am trying to match looks like this: # this is block1 /// text /// text /// text /// text # this is block2 /// text // ...

Why isn't the ajax table showing up in my HTML?

I am facing an issue while trying to run an application that involves AngularJS, Ajax, and a Java Controller returning JSON. Despite my efforts, the table is not displaying in the HTML. I am new to working with Ajax and AngularJS, and need assistance troub ...

What is the proper way to retrieve the value of the key "order" from this JSON object (containing semicolons in the name)?

Vijay Anand inquired about this particular matter yesterday, unfortunately, the discussion was closed before receiving any solutions: HTTP Response: { "entry": { "@xml:base": "https://API_PROC_SRV/", "@xmlns": "http://www.w3.org/2005/Atom", ...

When dynamically accessed, the property of a JSON object is considered "undefined"

I'm running into trouble trying to access properties of a JSON object in my JavaScript code using obj[varWithPropName]. Strangely, it does work when I use obj["PropName"]. Here's a simplified snippet for reference: import * as CharInfo from &ap ...

The NextJS homepage and API endpoint are combined on a single page

In my Next.js application, I have multiple pages and I want the component loaded at http://localhost:3000/someEndpoint to be exactly the same as the one loaded at http://localhost:3000/ I have already created an index.js file, but I am unsure how to creat ...

Exploring ways to transfer a function variable between files in React

Currently, I am working on a quiz application and have the final score stored in a function in app.js. My goal is to generate a bar graph visualization of the user's results (e.g. 6 right, 4 wrong) based on this score. To achieve this, I created anoth ...

By using .innerHTML to create an element, the validation of HTML form fields can be circumvented

After inserting a form field with standard HTML validation constraints (pattern & required), using the .innerHTML property does not trigger validation. While I understand the difference between creating an element with .innerHTML and document.createElement ...

Encountered an issue when attempting to select the password field in order to log into a Google account using

Having some trouble automating the login process for my Gmail account. Managed to find the email element with an ID, but hitting a roadblock trying to locate the Password element as it doesn't have an ID. Here's what I've attempted: passw ...

How to assign a new type to a class in Typescript

I am attempting to re-export a class with an internal type declaration in Typescript. My goal is for the re-exported class to be usable both as a class (with new) and as a type. Below is an example of what I have tried: class XReal { foo() {return 5} } dec ...

AngularJS ng-repeat is not updating when the state changes

Seeking assistance with an Angular application challenge I'm facing. I have implemented a ng-repeat in my app to display the latest messages stored in an array within a controller named "comunicacion": ng-repeat in comunicacion.html <div class=" ...

What are the advantages of utilizing buffer geometries in Three.js?

I have experience using both BufferGeometry and Geometry, so I feel comfortable with either. Even when I need to make frequent modifications, I tend to lean on BufferGeometry because although the code is more verbose, it's not overly complex. Can you ...

Retrieve the Vue.js JavaScript file from the designated static directory

This is my inaugural attempt at creating a web application, so I am venturing into Vue.js Javascript programming as a newcomer. I have chosen to work with the Beagle Bootstrap template. Within my Static folder, I have a file named app-charts-morris.js whi ...

Effortlessly initiate the consecutive playback on SoundCloud

I'm currently working on my music blog and I'm looking for some guidance in implementing a feature where the widgets start playing one after the other. Specifically, I have both SoundCloud and YouTube widgets, but I would like to focus on achievi ...

"Troubleshooting Angular: Uncovering the Root of the Issue with

I have set a specific pattern for the email field which should follow this format: pattern="^(([^<>()\[\]\.,;:\s@\']+(\.[^<>()\[\]\.,;:\s@\']+)*)|(\'.+\'))@(( ...