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

Vue.js2 - Detection of Observer in Array

A question for beginners in vue.js. I am trying to display data using the CanvasJS Library that is received via websocket. Everything works fine with the data until I introduce vue components into the mix. Let me clarify: export default { data() { r ...

Does type conversion have a specific ranking of preference?

When working with JavaScript, it's important to note that the language automatically converts types when necessary. For instance, if you have an expression like "8" * "3", JavaScript will convert the strings to numbers and calculate the result as 24. ...

Storing ajax data into a variable seems to be a challenge for me

I am facing an issue with my ajax call where I am receiving the data correctly, but I am unable to assign it to a local variable named item_price. The data that I am receiving can either be 100.00 or 115.25. Below is the snippet of my ajax code: $.ajax({ ...

What is the process for producing multiple objects in JSON format and then accessing them from within <g:javascript> in Grails?

My goal is to add two select boxes within the results div using Ajax. I have a function named ajaxFun that retrieves values for the select boxes. However, I am struggling with rendering multiple objects as JSON and then retrieving them in my JavaScript fun ...

Retrieve all original elements from FormGroup

While working on a Reactive Form in Angular, one of my goals is to enable scrolling within the native element if any control within the form group is invalid. However, there are various other reasons for needing access to the native element, making it just ...

Angular 7 is taking an unusually long time to load the after login component

Upon logging into my Angular 7 application, the after-login component experiences slow loading for the first time. However, if a user logs out and then logs back in without closing the browser, the speed improves. The routing structure is as follows: In ...

Exploring the possibilities of combining Selenium Code and F# with Canopy

Currently, I am facing the challenge of incorporating Selenium code into my F# project while utilizing the canopy wrapper. Canopy relies on Selenium for certain functions. My main struggle lies in converting Selenium code from Java or C# to fit within an ...

Are there any other methods of using HREF in an <asp:Button> besides OnClientClick for invoking an inline div?

I decided to create a concealed <div> on the same page and tried calling it with href="#", which worked perfectly. However, when I attempted to use the same code in ASP.net, I encountered some issues with Javascript or other factors that prevented it ...

JQuery ID Media Queries: Enhancing responsive design with targeted

Is it possible to integrate a media query into the selection of an ID using JQuery? For example: $('#idname') $('@media (max-width: 767px) { #idname }') In essence, can you target the #idname with that specified media query in JQuery ...

Guide on attaching an onclick event to a button created with a string in Next.js?

<div onClick={(event) => this.addToCart(event)}> <ReactMarkdownWithHtml children={this.props.customButton} allowDangerousHtml /> </div> In my current situation, I am facing an issue with the code above. The button is being rendered ...

Utilizing global variables in Vue.js while working with the CLI template

How can I create a global variable in my Vue.js app that is accessible by all components and modifiable by any of them? I am currently utilizing the CLI template. Any recommendations on how to achieve this? Appreciate your assistance. Dhiaa Eddin Anabtaw ...

RegEx - Finding exact matches without any additional characters trailing

I am currently trying to find matches in the given strings: 'Los Angeles, CA' 'New York, NY' 'Williamsburg, Brooklyn, NY' by comparing them with the following input strings: 'Los Angeles, CA 90001, USA' 'New ...

Feeling puzzled about the next() function in Node.js?

https://github.com/hwz/chirp/blob/master/module-5/completed/routes/api.js function isAuthenticated (req, res, next) { // If the user is authenticated in the session, call the next() to proceed to the next request handler // Passport adds this met ...

Using jquery to dynamically retrieve the unique property identifier

I have a dynamically generated table with a button labeled as view images. Each time this button is clicked, I need to retrieve the image names from the database for that specific property. <?php foreach($unapproved as $unapp):?> < ...

I encountered an issue with Array map when attempting to access the data during a dynamic rendering process

function UserTransactionsComponent1() { const [accounts, setAccounts] = useState(); useEffect(() => { async function fetchData() { const res = await fetch( 'https://proton.api.atomicassets.io/atomicassets/v1/accounts' ...

Issue with react-router-dom loader defer type issue

I attempted to troubleshoot the issue with data loading by incorporating defer in the loader function. I am unsure how to specify the postResponse type, which represents the actual response data. Even after experimenting with type casting and other m ...

Display text when hovered over or clicked to insert into an HTML table

I have an HTML table connected with a component field gameArray and I need it to: Show 'H' when the user's cursor hovers over TD (:hover) and the corresponding field in gameArray is an empty string, Fill the gameArray field after a click. ...

TinyMCE file multimedia upload feature allows users to easily add audio, video

I am looking to enhance the functionality of my TinyMCE Editor by enabling file uploads for audio/video and images. Although image uploading is functioning properly, I am encountering issues with other types of files. Despite setting up pickers throughout, ...

The Sortable feature is functional in all browsers except for Firefox

I am currently utilizing the following example () within my asp.net application. I have successfully implemented the sortable feature in all browsers except for Firefox, where it seems to trigger the event but doesn't execute the code. $('.c ...

Prohibit the Use of Indexable Types in TypeScript

I have been trying to locate a tslint rule in the tslint.yml file that can identify and flag any usage of Indexable Types (such as { [key: string] : string }) in favor of TypeScript Records (e.g. Record<string, string>). However, I haven't had a ...