"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

Tips for displaying only the initial 15 characters of a text value

The content extracted from a .ts file is being displayed on the home.html page. I am aiming to display only the initial 15 characters followed by 3 dots (...). Despite my efforts, the following code snippet is not functioning as expected: home.html < ...

Replacing child routes with an Angular wildcard route

I'm facing an issue with integrating a module named "host" into the app-routing.module. The problem I encountered is that the wildcard route takes precedence over loading the Host component, leading to the display of the PageNotFoundComponent instead. ...

Angular 2 component downgrade issue: What causes the error when constructor parameters are involved? (SystemJS) Unable to resolve all parameters for (?)

Consider this line as an example: constructor(private elementRef: ElementRef, private zone: NgZone) {} In order for the downgrade to be successful without any errors, I must remove the parameters from the constructor. Otherwise, I encounter the follo ...

Caution: the index of the array is outside the boundaries of the array [-Warray-bounds] within the

static int myarray[2]={-1,234}; module_param_array(myarray,int,&arrayargc,0); MODULE_PARM_DESC(myarray,"Integer Array"); static int __init module_init_2(void) { int i; for(i=0;i< (sizeof myarray/sizeof(int));i++); { printk(KERN_INFO "mya ...

Angular 8 does not show the default option in the select tag

When I use the following code snippet: <div style="text-align:center"> <form> <select type="checkbox" name="vehicle1" (change)="onchange()" > <option> 1 </option> <opti ...

Utilizing v-for in Vue with TypeScript to generate multiple checkboxes

My goal was to capture the values of checkboxes and store them in an array using v-model. However, I encountered an issue where the first time I toggle a checkbox, it doesn't register. Only after checking a second box and hitting submit does the secon ...

What is the best way to find the actual position of this user within my array?

I found this example in the Vue JS documentation here When using a filtered v-for, how can I obtain the actual index of a user in the array, rather than the index of the current iteration? <div id="filter-by-example"> <ul> <li v-for= ...

Utilizing TypeScript interfaces to infer React child props

How can I infer the props of the first child element and enforce them in TypeScript? I've been struggling with generics and haven't been able to get the type inference to work. I want to securely pass component props from a wrapper to the first ...

Can you explain how this promise functions within the context of the mutation observer, even without an argument?

Recently, I came across a mutation observer in some TypeScript code that has left me puzzled. This particular implementation of a promise within the mutation observer seems unconventional to me: const observer = new MutationObserver((mutations: MutationR ...

Path expression is not valid as it attempts to access an element

When attempting to modify a single element in an array, I encounter the error message Invalid path expression near attempt to access element. Interestingly, this issue only arises when the array is obtained from --rawInput. For instance: # input: [ 1, 0 ...

What is the best way to merge two similar arrays of objects into one array object?

Apologies in advance if this question has been asked previously, I'm struggling with how to phrase it. Essentially, the API I'm using is returning an array of similar objects: const response.survey = [ { 1: { id: 1, user: user_1, points: 5 ...

The display of buttons in Ag-Grid Cell Render is not appearing correctly when integrated with Angular Material tab component

Recently, I integrated ag-grid into one of my projects and successfully created a Cell Renderer to showcase buttons in the "actions" columns. However, when I transferred the grid into an Angular material, I noticed a peculiar issue. Upon navigating to the ...

Modifying a single element within a struct array will result in modifications being applied to all elements

My goal is to modify variables of structs within an array, but I've encountered an issue where changing one variable affects the others in the array as well. I've attempted using -> and (*logEntries[i]), but neither method seems to work as int ...

Setting up and Building Arrays of Objects in C++

When initializing an array of objects, do all the objects get constructed immediately or is construction required after initialization? To illustrate this scenario, consider the following: Suppose we have a class like this: class Object{ public: int ...

Struggling to locate the module 'firebase-admin/app' - Tips for resolving this issue?

While working with Typescript and firebase-admin for firebase cloud functions, I encountered the error message "Cannot find module 'firebase-admin/app'" when compiling the code with TS. Tried solutions: Reinstalling Dependency Deleting node_modu ...

The deprecation of DynamicComponentLoader in Angular 2 rc4 is now in effect

I am currently in the process of updating my Angular 2 application from beta.14 to rc.4. Upon moving to @angular/core, I encountered a deprecated warning related to DynamicComponentLoader. Can someone provide guidance on the new Class that should be used ...

Guide on adding an image along with additional data to a designated folder within the Google Drive app and retrieving it in JSON format within the app using Swift

After successfully integrating the Google Drive sync using this link with the source code, I am facing an issue. I am unable to upload images with their name, id, and location to the app specific private folder. I need to upload images along with other fi ...

Having trouble importing Bootstrap CSS into a TypeScript file

I'm having trouble importing the bootstrap css file from node_modules. It's not importing, even though I can import the scss file successfully. The following import is not working: import bs from "bootstrap/dist/css/bootstrap.css"; Ho ...

Changing the ngModel value causes the maxlength to become ineffective

<input type="text" [(ngModel)]="name" maxlength="10"/> @Component({...}) export class MyComponent { name = "testtesttesttesttest"; // length = 20 } When the input field is displayed, it shows all 20 characters. What steps can be taken to prevent ...

Unable to access any pages using the angular-cli http-server for deployment

When I run my project using 'ng serve', everything works fine. However, when I deploy it on a server using 'http-server ./dist', none of the pages can be accessed and an error message is displayed: host:~/morange/project$ http-server . ...