"Implementing a Filter for Selecting Multiple Options in Ionic Framework

I need help with filtering books in an online library project using a modal page. The modal has 3 input fields for title, author, and year. How can I filter the books based on these inputs?

Here is a snippet of my modal.html code:


    <ion-content padding>
      <ion-list>
        <ion-item>
          <ion-label color="primary">Title</ion-label>
          <ion-input placeholder="Insert the title" [(ngModel)]="searchTerm" name="titlebook"></ion-input>
        </ion-item>
        <ion-item>
          <ion-label color="primary">Author</ion-label>
          <ion-input placeholder="Insert the Author" name="authorbook"></ion-input>
        </ion-item>
        <ion-item>
          <ion-label color="primary">Year</ion-label>
          <ion-input type="number" placeholder="Insert the Years" name="anno"></ion-input>
        </ion-item>
      </ion-list>
      <ion-buttons text-center>
        <button ion-button color="secondary" (click)="searchTitle()">save</button>
      </ion-buttons>

Example of JSON data for one book from my collection (100 books):


    {
      "id":"3",
      "author": "Dante Alighieri",
      "country": "Italy",
      "imageLink": "images/the-divine-comedy.jpg",
      "language": "Italian",
      "link": "https://en.wikipedia.org/wiki/Divine_Comedy\n",
      "pages": 928,
      "title": "The Divine Comedy",
      "year": 1315
    },

Answer №1

Here's a straightforward method to accomplish this:

Set up a change event listener on your three input fields like so:

<ion-input (ionChange)="filterItems()"></ion-input>
.

Include your filterItems() function in your modal controller:

filterItems() {
    this.books.filter((item) => {
        // the logic within this block determines whether the item will be displayed or not
        return item.title.toLowerCase().includes(this.title.toLowerCase) && item.author.toLowerCase().includes(this.author.toLowerCase());
    });
}

Now you're filtering based on both the title and author. Remember to bind your ion-input's with ngModel.

You can then render your books using *ngFor in your template.

Be cautious! The function will return false if the inputs are empty. You may need to adjust the condition according to your requirements.

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

Next.js TypeScript throws an error stating that the object 'window' is not defined

When trying to declare an audio context, I encountered an error stating that window is undefined. I attempted declaring declare const window :any above window.Context, but the issue persists. Does anyone have a solution for this problem? window.AudioCont ...

What is the best way to connect the button value with my ng-model data?

I'm having trouble getting the button value to bind to my ng-model. Any suggestions on how I should approach this? Currently, I am utilizing the datepicker from https://github.com/rajeshwarpatlolla/ionic-datepicker <div class="col"> <labe ...

Managing numerous post requests with Angular

Dealing with a large form containing HTML input elements, I have implemented a functionality where a POST request is made to a WebAPI whenever there is a change in the input value. Sometimes, multiple POST requests are triggered within seconds, causing da ...

How is it possible for passing a number instead of a string to not result in a compilation error?

Here is some code that has caught my attention. It involves passing a number to a function that expects a string. const getGreeting: Function = (name: String): String => { return `hello, ${name}`; }; const x: number = 2 console.log(getGreeting(x)) ...

Having trouble getting Angular 2 animations to fade in

I've been trying to figure out how to make the html fadeIn for hours. Every time ngFor displays it, the opacity stays at 1 immediately, without fading in. FadingOut works fine, but the fadeIn effect is not working as expected. @Component({ selector:& ...

Troubleshooting deployment issues of an Angular 5 and ASP.NET Core 2.1 application on an nginx server

Trying to get my Angular 5 application deployed on Digital Ocean Ubuntu 16.4 Nginx, but running into some issues. I can successfully access the API endpoints: http:://ipaddress/api/values However, I am facing problems with the Angular website itself: T ...

What is the process for interpreting the status code retrieved from an HTTP Post request?

When sending a POST request to a backend and attempting to read the status code, I encountered the following result: status-code:0 Below are my functions: Service: signIn(uname:string, pass:string): Observable<any> { let headers = new Headers( ...

Is numpy's handling of 1-D slices of arrays unconventional?

import numpy as np a = np.array([[(1, 2, 3), 40, 50], [(4, 5, 6), 70, 80]]) Is there a way to create a 2-by-3 numpy array (matrix) [[1,2,3], [4,5,6]] from the given array 'a' using only numpy operations? Ideally, without explicit python-style li ...

When triggering the event: Was anticipating a spy, however received a Function instead

Upon running my test, I encountered the following error message: Error: Unhandled Promise rejection: <toHaveBeenCalledWith> : Expected a spy, but received Function. it('should change the value of myComponent', () => { spyOn(component ...

How long do route providers typically last?

When using standalone components, we have the ability to place services into route providers. I couldn't locate this information in the documentation - what is the lifespan of these service instances? Are they destroyed when the route becomes inacti ...

Troubleshooting and setting breakpoints in TypeScript code for Angular Web applications using the Firefox browser

Is there a method to add breakpoints to .typescript source files in my Angular application with Firefox Developer Tools? While I am able to add breakpoints to the generated javascript files, is it possible to debug the .ts source files directly? This quer ...

Why am I encountering an undefined value in my AngularJS code?

Can you explain why I am receiving an undefined value when clicking on the chart? I have created a bar chart and am attempting to retrieve the selected item and its value. The fiddle I provided displays the correct value: http://jsfiddle.net/b4n9z19v/ Ho ...

Encountering an error when attempting to store a value in an array of custom types: "Unable to assign properties to undefined (setting 'id')"

My model looks like this: export class SelectedApplicationFeatures { id: number; } In my TypeScript file, I imported the model as shown below: import { SelectedApplicationFeatures } from "src/app/models/selectedApplicationFeatures.model"; selec ...

Ways to establish the relationship between two fields within an object

These are the definitions for two basic types: type AudioData = { rate: number; codec: string; duration: number; }; type VideoData = { width: number; height: number; codec: string; duration: number; }; Next, I need to create a MediaInfo typ ...

Looking to organize an array of objects containing two string elements (countries) based on the country name using TypeScript or the Lodash library?

Below is an example of an array of objects I am working with: { countries: [{ "country_alpha2_code": "PW", "country_name": "PALAU" },{ "country_alpha2_code": "US&qu ...

Describing an Object with some typed properties

Is there a method to specify only a portion of the object type, while allowing the rest to be of any type? The primary objective is to have support for intelliSense for the specified part, with the added bonus of type-checking support. To demonstrate, let& ...

Setting up D3 on a Meteor Angular2 project

Currently, I am attempting to combine D3 and topojson within the context of Meteor + Angular2. import { Component } from '@angular/core'; import template from './d3map.component.html'; * import 'd3' @Component({ selector: ...

"Data in Fusioncharts appears to be correctly formatted, but it is having difficulties

I am developing a financial analysis tool and I need to visualize stock data using fusion charts. Currently, my dataset includes stock values along with their respective dates: $scope.chartData = [ { "label": "2017-05-11 16:00:00", "value": "930.6" } ...

What are the advantages of utilizing the HttpParams object for integrating query parameters into angular requests?

After exploring different ways to include query parameters in HTTP requests using Angular, I found two methods but struggled to determine which one would be the most suitable for my application. Option 1 involves appending the query parameters directly to ...

Utilize the routerLink within a string value on a HashMap instance

I am currently storing translated parameters in a HashMap object on my component. However, I am facing an issue where certain attributes such as [routerLink] are not functioning properly or not being interpreted by Angular (v5). Here is the code snippet f ...