Ways to filter and display multiple table data retrieved from an API based on checkbox selection in Angular 2 or JavaScript

Here is a demonstration of Redbus, where bus data appears after clicking various checkboxes. I am looking to implement a similar filter in Angular 2.

In my scenario, the data is fetched from an API and stored in multiple table formats. I require the ability to filter across multiple tables.

Essentially, I need the feature that filters the data from the tables when certain checkboxes are selected.

<!--Checkboxes section: using 'bus' and 'fare' as examples-->
<div class="filter2" id="myUL">
    <div class="search">
        <i class="fa fa-search"></i>
        <input class="search-box" type="text" placeholder="" id="myInput" onkeyup="myFunction()">
    </div>
    <label class="containe">Fare
        <input type="checkbox">
        <span class="checkmark"></span>
    </label><br/>
    <label class="containe">Bus
        <input type="checkbox">
        <span class="checkmark"></nbsp;</span>
    </label><br/>

</div>

<!--Table section starts here-->
<table class="col-xs-12 col-sm-12 col-md-12 col-lg-12 main-bus-table">
    <!-- Search result table -->
    <ng-container *ngFor="let bus of this.global.getSearchResult.data.onwardSearch ">
        <!-- Filter results container -->
        <tr class="busrow">
            <div class="row">
                <div class="col-xs-0 col-sm-0 col-md-1 col-lg-1 busdiv-pad">
                </div>
                <div class="col-xs-12 col-sm-12 col-md-10 col-lg-10 bus-details">
                    <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 buslogo">
                        <img src="assets/img/bus1.svg" height=44px width=44px>
                        <div class="rating-circle">5.0</div>
                    </div>
                    <div class="col-xs-12 col-sm-12 col-md-11 col-lg-11">
                        <table class="wd-100 bus-table">
                            <tr>
                                <td class="wd-30 busname"><p>{{bus.operatorName}}<span class="gps">GPS</span></p></td> <!-- Bus name -->
                                <td class="wd-30 timing"><p>{{bus.departureTime}} <img src="assets/img/to1.svg"> {{bus.arrivalTime}}</p></td> <!-- Bus time -->
                                <td class="wd-20 seats-left"><p>Total Seats : {{bus.availableSeats}}</p></td> <!-- Bus available seats -->
                                <td class="wd-20 price"><p><i class="fa fa-rupee"></i>{{bus.fare}}</p></td> <!-- Bus fare -->
                            </tr>
                            <tr>
                                <td class="wd-30 bustype"><p>{{bus.vehicleClass}}</p></td> <!-- Bus type -->
                                <td class="wd-30 distance"><p>06h 30m/340km</p></td> <!-- Bus total distance -->
                                <td class="wd-20 windowseats"><p>1 Window</p></td> <!-- Bus total window seats -->
                                <td class="wd-20 revisedprice"><p><i class="fa fa-rupee"></i>{{bus.fare}}</p></td> <!-- Bus revised fare -->
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </tr>
    </ng-container>
</table>

Thank you in advance for any assistance with my issue.

Below is a screenshot showcasing the Redbus filter example:

https://i.stack.imgur.com/pcTHe.png

Answer №1

To begin, store the input content in variables.

searchTerm: string = '';
filterOptionOne: string = '';
check...

The next step is to use Pipes:

Here is an example:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
 name: 'searchFilter'
})
export class SearchFilterPipe implements PipeTransform {

transform(value: any, searchTerm: string): any {
 if  (!searchTerm) {return value;}
  let result = value.filter(item => {
   if ( !item.location ) {return;}
    return item.location.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1;
  });
 return result;
 }

}

Repeat the process for all types of values, then apply all pipes like this:

<ng-container *ngFor="let dataItem of this.global.getFilteredData.data.filteredItems | searchFilterPipe: searchTerm | filterOptionOnePipe: filterOptionOne">

That's it. I hope that explanation was clear.

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 necessary to test the main.js file in Vue.js project?

While performing unit tests on components is acceptable, after running coverage analysis I have noticed that certain lines of code in the main.js file remain uncovered. This raises the question: should the main.js file also be included in testing? Specifi ...

Error message: When initiating AJAX requests in ASP.NET, the function is not defined for undefined

I recently followed a tutorial on creating AJAX requests for CRUD operations in an AngularJS application. However, upon trying to perform an AJAX request to retrieve data from the database, I encountered the following error when launching my application: ...

What could be the reason for the emptiness of my AngularJS scope object?

The code snippet in my controller looks like this: app.controller("weeklyLogViewer", function ($scope, $http){ $scope.allLogs = {}; $http({ method: 'POST', url: '../Utilities/WeeklyLog.php', data: $scope.dateSelected, ...

Execute a query to retrieve a list of names and convert it to JSON using Unicode encoding in

Just starting out with Laravel and I'm trying to figure out how to execute some queries Not talking about the usual select statements... I need to run this specific query: SET NAMES 'utf8' First question, here we go: I have Hebrew ...

Filtering Jquery datatable results by text

In order to filter records from a jQuery data table, I have utilized the following code. The format for my data table is as follows: var aDataSet = [['1', 'GOld', 'G-110,G-112,G-123', 'G1-001,G1-005,G1-008'], ...

Is there a way to broadcast a message to all the Discord servers where my bot is currently active using v14 of discord.js?

Can someone assist me in creating code that allows me to send a message to all servers at my discretion? I have not found any resources on this topic for discord.py or the newer versions of discord.js ...

Is it possible to pass a parameter to a PHP controller using JavaScript without relying on jQuery or AJAX?

Is it possible to achieve the task at hand? That's the main question here. My goal is to extract data from a popup window and then, upon closing it, send this extracted content to a PHP controller for further processing. I'm facing conflicts wi ...

Can someone guide me on capturing an API response error using observables?

Currently working with Angular 4, my API call is functioning properly, returning the expected JSON for successful responses. However, in case of an error response, instead of receiving a JSON response as expected, I end up with a 404 HTML page (which is no ...

Issue with Angular cookies not being able to remove the cookie within a Chrome extension

I am currently developing a Chrome extension that includes login and logout features. After a successful login, the server sends a token that I need to store in a cookie. The process looks like this: function success(response) { if(response.data & ...

Unusual marker appearing on every page utilizing ionic v1 and angularjs

For some unknown reason, a dot appears at the upper left side of each page in my webapp: https://i.stack.imgur.com/nN61t.png It seems to be an issue with the HTML code. When I run the snippet below, the dot is visible: <ion-view view-title="Send fe ...

The NEXT_LOCALE cookie seems to be getting overlooked. Is there a mistake on my end?

I am looking to manually set the user's locale and access it in getStaticProps for a multilingual static site. I have 2 queries: Can a multilingual website be created without including language in the subpath or domain? Why is Next misinterpreting m ...

The error message "Cannot read property 'addEventListener' of undefined" occurred while trying to register the service worker using `navigator.serviceWorker.register('worker.js')`

I'm grappling with a JavaScript issue and need some help. You can find the demo of the functioning script by the author right here. I've implemented the same code as displayed on his demo page. I've downloaded the worker.js file and ...

Disable the loader for a specific method that was implemented in the Interceptor

Custom Loader Interceptor A loader has been implemented within an Interceptor. I have a specific requirement where the loader should not be triggered during the upload() function. It should not be applied to that particular method only. ...

problem with passing the identification number into the function

I am facing an issue with passing the id into a javascript onClick method. I am using the Spring framework and in the controller class, I send the related id to the JSP file like this: model.addAttribute("uploadid", uploadid); Afterwards, I need to p ...

Master the art of properly switching on reducer-style payloads in Typescript

Currently, I am dealing with two types of data: GenArtWorkerMsg and VehicleWorkerMsg. Despite having a unique type property on the payload, my Searcher is unable to differentiate between these data-sets when passed in. How can I make it understand and dis ...

Is a fresh connection established by the MongoDB Node driver for each query?

Review the following code: const mongodb = require('mongodb'); const express = require('express'); const app = express(); let db; const options = {}; mongodb.MongoClient.connect('mongodb://localhost:27017/test', options, fu ...

How can you set an input field to be initially read-only and then allow editing upon clicking a button using Vue.js?

//I have two divs that need to be set as readonly initially. When an edit button is clicked, I want to remove the readonly attribute and make them editable. <div> <input type="text" placeholder="<a href="/cdn-cgi/l/email-protection ...

Using JQuery's appendTo method with a lengthy string of elements that includes a mix of single and double quotes: a step-by-step guide

My content script is fetching data from the server in the form of an array of objects. The structure looks something like this: [ { "lang": "English", "videos": [ { "embed": "<iframe width='100%' height='421px&apo ...

Transferring information from a Nuxt module to a plugin

I have been working on passing data from my module options to a plugin. Here is an example of how I am doing it: module.exports = function (moduleOptions) { const options = { ...this.options.moduleName, ...moduleOptions } this.addPlugin({ ...

What is the best way to retrieve unique column values using the LoopBack REST API?

I am working with a loopback REST API that fetches data from a MySQL table and returns it in JSON format. However, I need to apply a filter or query so that only distinct values for a specific column are returned. In SQL, we use the syntax SELECT DISTINC ...