Searching Local JSON Data in Ionic 4 with a Filter Input Bar

My current challenge involves filtering local JSON data in my Ionic project. Despite referencing other resources, I am unable to filter or display filtered items on the ngx-datatable. I suspect the issue may lie either in the filterItems function implementation or how the data is loaded from the local JSON file. Any guidance on this matter would be greatly appreciated. Below are the HTML and TypeScript code snippets:

HTML code

<ion-header>
  <ion-toolbar color="primary">
    
    <ion-buttons slot="start" class="button_style">
      <ion-button (click)="switchStyle()">
        {{ tablestyle }}
      </ion-button>
    </ion-buttons>
 
    <ion-searchbar animated  slot="end"  (ionInput)="filterItems($event)" placeholder="Search by Path Request"></ion-searchbar>

  </ion-toolbar>
</ion-header>
 
<ion-content>

    <ngx-datatable  class="request_table"
    [ngClass]="tablestyle" 
    [rows]="items"
    [columnMode]="'force'" 
    [headerHeight]="50" 
    [rowHeight]="'auto'">
 
    <ngx-datatable-column name="requestid"></ngx-datatable-column>
    <ngx-datatable-column name="number"></ngx-datatable-column>
    <ngx-datatable-column name="requeststatus"></ngx-datatable-column>
    <ngx-datatable-column name="animalcount"></ngx-datatable-column>
    <ngx-datatable-column name="primaryinvestigator"></ngx-datatable-column>
    <ngx-datatable-column name="studypathologist"></ngx-datatable-column>

    <ngx-datatable-column name="Actions" sortable="false" prop="name">
      <ng-template let-row="row" let-value="value" ngx-datatable-cell-template>
        <ion-button size="small" fill="outline" (click)="goToProcedureDetails(row)">View</ion-button>
      </ng-template>
    </ngx-datatable-column>
 
  </ngx-datatable>
 
</ion-content>

Typescript code

import { AlertController } from '@ionic/angular';
import { HttpClient } from '@angular/common/http';
import { Router, ActivatedRoute } from '@angular/router';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';


@Component({
  selector: 'app-request',
  templateUrl: './request.page.html',
  styleUrls: ['./request.page.scss'],
})
export class RequestPage implements OnInit {

  items: any[];
  searchItems: any;
  public RequestFilter: string[];
  tablestyle = 'bootstrap';

  constructor(private alertCtrl: AlertController, private http: HttpClient, private router: Router) { }

  ngOnInit() {
    this.loadData();
  }

  loadData(){
    let data:Observable<any>;
    data = this.http.get('assets/requests.json');
    data.subscribe(data => {
      this.items = data;
      console.log(this.items);
    });
    this.initializeItems();
  }

  initializeItems(){
    this.RequestFilter = this.items;
  }

  goToProcedureDetails(row){
    this.router.navigate(['/view-procedure', row.pathrequestid]);
    console.log(row.pathrequestid);
  }

  filterItems(ev:any){
    // Reset items back to all of the items
    this.initializeItems();

    // set val to the value of the searchbar
    var val = ev.target.value;

    // if the value is an empty string don't filter the items
    if (val && val.trim() != '') {
      this.RequestFilter = this.items.filter((item) => {
       return (item.toString().toLowerCase().indexOf(val.toString().toLowerCase()) > -1);
     })
    }
  }
}

Answer №1

It seems like your code isn't functioning properly because you are filtering on an object.

items: any[];
return (item.toString().toLowerCase().indexOf(...

If you want to filter based on a specific column (such as the requeststatus column), you can achieve that with the following:

return (item.requeststatus.toString().toLowerCase().indexOf(val.toString().toLowerCase()) > -1);

If you wish to filter on all columns of the table, I recommend checking out this question for more insights.

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

Angular routing is giving me trouble when trying to open various menus at the same location

I am new to Angular and facing a situation where my HomeComponent has a reference to the Appmenucomponent in its .html page. I need to be able to click on different menus (each leading to a new component) and have them open in the same place (div), similar ...

Angular 5 APP_INITIALIZER: Provider parse error - Cyclic dependency instantiation not possible

I am utilizing the APP_INITIALIZER token to execute a task upon page load before my Angular application is initialized. The service responsible for this functionality relies on another service located within my CoreModule. The issue at hand seems to be ab ...

Incorporating @angular/fire into the latest version of Angular, version

I need help incorporating @angular/fire into my Angular 12 project for deployment on Firebase. After using the CLI to add @angular/fire, I ran the following command: ng add @angular/fire The output displayed was as follows: ℹ Using package manager: npm ...

What's the best way to convert static data from JSON files within the Django framework?

I am dealing with a json file that contains an extensive list of geographic locations [ { "id": 1, "name": "Afghanistan", "iso3": "AFG", "iso2": "AF", ...

pdfMake introduces a page breaking effect when the canvas is utilized with the type "line"

Can anyone shed some light on why a canvas declaration with the type "line" is causing a page break in the generated PDF? I've tried removing all canvases and the page break disappears, but I can't identify the root cause. Any insights would be ...

Running frontend and backend applications together in a Docker container

As I work on integrating my frontend in Angular with the corresponding backend in Spring Boot, both as standalone projects, I am now looking to transition them into production mode. This has led me to consider hosting each project in separate docker contai ...

Is it possible to obtain the return type of every function stored in an array?

I'm currently working with Redux and typesafe-actions, and I am trying to find a way to automatically generate types for the actions in my reducer. Specifically, I want to have code completion for each of the string literal values of the action.type p ...

An issue occurred in the modal window following the relocation of project files

I encountered an issue with the modal in my Nativescript project after rearranging a few project files, including the modal. I updated the imports and deleted any compiled JavaScript files to ensure that my project could recompile correctly. Although I&ap ...

Is there a way to filter and tally the JSON objects that have latitude and longitude within a 10km radius from the

I'm currently working on filtering and counting objects from an API endpoint that fall within a 10km radius of the specified origin. My main challenge lies in correctly filtering the API results and tallying the number of matching items. While I succ ...

Struggling to effectively work with ArrayForm when trying to include additional form fields

I'm attempting to add a playlist in Mat-dialog that contains songs in a list using (formArray) as shown here: https://i.stack.imgur.com/diWnm.png However, I am unsure of the mistake I might be making This is how my dialogue appears: https://i.stac ...

The timer functionality in the Angular 2+ component is malfunctioning

This situation is quite perplexing. I have a timer function that works perfectly on all my components except one. Strangely, I can't seem to figure out why this particular component is not cooperating, especially since there are no error messages appe ...

How can one determine the source of change detection activation in Angular 2?

I just launched a new component and it appears to be causing change detection to occur multiple times per second: // debugging code ngDoCheck() { console.log('DO_CHECK', new Date().toLocaleTimeString()); } Results: https://i.sstatic. ...

Resetting ng-select values in an Angular application: A quick guide

Currently, I am utilizing ng-select within a modal window. <div class="modal-body"> <div class="form-group has-feedback"> <ng-select #select name="currenies" [allowClear]="true" [items]="currencyList" [disabled]="disabled" (selected)="sel ...

Retrieving Color Values from Stylesheet in TypeScript within an Angular 2 Application

Utilizing Angular2 and Angular Material for theming, my theme scss file contains: $primary: mat-palette($mat-teal-custom, 500, 400, 900); $accent: mat-palette($mat-grey4, 500, 200, 600); There is also an alternate theme later on in the file. Within one ...

Using SystemJS to re-export modules does not function properly

Attempting to re-export modules according to the TypeScript language website - using SystemJS as the module loader: app.ts import * as s from "./AllValidators"; // Some samples to try let strings = ["Hello", "98052", "101"]; // Validators to use let v ...

Unlock the full potential of working with TaskEither by utilizing its powerful functionality in wrapping an Option with

After exploring various examples of using TaskEither for tasks like making HTTP requests or reading files, I am now attempting to simulate the process of retrieving an item from a database by its ID. The possible outcomes of this operation could be: The i ...

Tips for creating a webfont using SVG icons

Seeking advice on generating a webfont from SVG icons using webpack, angular2, and typescript. Any suggestions on the best way to achieve this? Struggling to find helpful information online. Please lend a hand! https://i.sstatic.net/kvClK.png The code pr ...

TypeScript encounters a problem when attempting to concatenate arrays with different signature overloads

I encountered the following error message: There is an issue with overloading. Overload 1 of 2, '(...items: ConcatArray<{ title: string; width: number; dataIndex: string; render: (level: string) => Element; }>[]): { title: string; width: nu ...

Learning to pull data from a JSON file using Java

Being a novice programmer, I am attempting to create my first small project that involves extracting values from a JSON file and then displaying them on a JavaFX line chart. Despite my efforts to find a solution using json.simple or json.org libraries, I h ...

I'm looking for a sample of RadPieChart for nativescript + angular. Can anyone help me out?

I'm currently working on a multi-platform application that requires a PieChart to be displayed on the main screen. Can someone point me to a comprehensive example of how to implement this? I have tried following this guide and modifying it according ...