Implementing a personalized pipe to enhance search functionality in a data table

I am currently working on a project that involves displaying data in a table. I want to add a search bar functionality that allows users to filter the table data. I have attempted to use a pipe to achieve this, but I am facing challenges and unsure of the correct approach.

The data in the table is sourced from a local json file stored in the assets folder. The table structure is defined in the app.component.html file.

I have already created a pipe for filtering, but I am stuck on writing the necessary code inside it.

Here is a basic example of what I am trying to achieve, where the data is displayed in a table sourced from a local file:

https://stackblitz.com/edit/angular-5ujgcy

Here is the code snippet I have so far:

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

@Pipe({
  name: 'countrysearch'
})

export class CountrysearchPipe implements PipeTransform {
  transform(Country: any[], searchText: string): any[] {
    if(!Country) return [];
    if(!searchText) return Country;
    searchText = searchText.toLowerCase();
    return Country.filter( it => {
      return it.toLowerCase().includes(searchText);
    });
   }
}

//html

<input [(ngModel)]="searchText" placeholder="Enter search text">
    <ul>
        <li *ngFor="let country of Countries | filter : searchText">
        {{countries.Name}}
        </li>
    </ul>

    <table border="1">
        <!-- ADD HEADERS -->
        <tr>
            <th>>Name</th>
            <th>People</th>

<tr *ngFor="let country of Countries ">
            <td>{{ country.Name }}</td>
            <td>{{ country.People }}</td>
</tr>
</table>

Answer №1

The issue arises from the mismatch in the pipe name, where it is being referred to as countrysearch in the code, but in the HTML file, it is written as filter: searchText. The correct syntax should be countrysearch: searchText

If not, you can alternatively update the pipe.ts file to use the name filter instead of countrysearch

Answer №2

As Richard suggested, make sure to update your Pipe to 'countrysearch' in the code below:

<li *ngFor="let country of Countries | countrysearch : searchText">
        {{countries.Name}}
 </li>

Additionally, ensure you include null handling and property filtering for the 'Name' attribute in the pipe to prevent any errors:

export class CountrysearchPipe implements PipeTransform {
  transform(Country: any[], searchText: string): any[] {
    if(!Country) return [];
    if(!searchText) return Country;
    if(Country && Country.length > 0){
      searchText = searchText.toLowerCase();
      return Country.filter(it => {
        return it.Name.toLowerCase().includes(searchText);
      });
    }
  }
}

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

Jodit-React: Addressing the Placeholder Problem

I've recently incorporated Jodit-react into my react-typescript project, but I encountered an error when adding the config property. The error message stated that it "Has no property common with type." Unfortunately, I'm unsure why this is happe ...

What could be causing the error message 'Why is 'push' property undefined in React Native?

Within my index.ios.js file, I have the following: renderScene(route, navigator){ return <route.component navigator={navigator} {...route.passProps}/> } as well as render() { return ( <Navigator initialRoute={{name: &a ...

Delay the rendering of the MUI DataGrid column until after the DataGrid is visible on the screen

Would it be feasible to asynchronously load a column of data in the MUI DataGrid after the table is displayed on the screen? Retrieving this additional data from the database is time-consuming, so I aim to have it appear once the table has fully loaded. T ...

``How can I lock the top row of an HTML table containing input fields in place while

Below is the table structure: <table> <tr> <th>row1</th> <th><input type="text"></th> <th><input type="text"></th> <th><input type="text"></th& ...

Mapping an object in a table only results in the final value being displayed

I am facing an issue with my data object containing an array of data that I have mapped inside a table. The problem arises when I try to retrieve the id value of any item in the table's rows using console.log(). It always returns the id of the last it ...

What is the reason for the compatibility issue between sass-loader and Angular?

One of my rules for dealing with sass is as follows: { test: /\.(scss|sass)$/, use: [ { loader: 'raw-loader'}, { loader: 'sass-loader', options: {data: sassConfiguration} } ], } typescript loader { ...

Retrieving journal web addresses using the CORE API

I am currently working on pulling journal data from the CORE API in React, specifically focusing on obtaining the title and URL of each journal. My goal is to create clickable links that direct users to the specified URLs. { "identifiers": [ ...

Leveraging hapi-auth-basic

I attempted to incorporate a basic authentication strategy following a tutorial I stumbled upon. Here is the setup of my server.js file. 'use strict'; const Hapi=require('hapi'); const sequelize = require('sequelize'); c ...

Working with arrays in Angular 4 to include new items

I am struggling with the code below: export class FormComponent implements OnInit { name: string; empoloyeeID : number; empList: Array<{name: string, empoloyeeID: number}> = []; constructor() { } ngOnInit() { } onEmpCreate(){ conso ...

Using multiple ng-controller directives with the "controller as x" syntax on a single element

What is the reason that Angular does not allow two ng-controller directives on a single element and What are some potential solutions for this issue - such as using custom directives or nesting HTML elements with a single ng-controller directive, among oth ...

Creating dynamically generated routes in Angular or Angular 9 before initialization

I'm currently working on a project where I am in the process of converting an AngularJS application to Angular. The main challenge that I am facing at the moment revolves around routing. To sum it up: My requirement is to define routes based on an AP ...

The function .play() cannot be executed on document.getElementById(...) - it is not a

There is an error in the console indicating that document.getElementById(...).play is not a valid function. import React from 'react'; const musicComponent=(props)=>{ const style={background:props.color} return( <div classN ...

Angular Material Mat-List-Option to display a collection of checkboxes and retrieve information

Here is a list of shoes I have: <mat-selection-list #shoes> <mat-list-option *ngFor="let size of customer.productsizes"> {{size .sizeName}} </mat-list-option> ...

The GraphQL Resolver function that returns an object

When querying with GraphQL, I receive results in the following format: { "data": { "events": [ { "_id": "65f0653eb454c315ad62b416", "name": "Event name", " ...

I'm having trouble getting the JADE tag to render in Express script. Can anyone help me

I am trying to include client-side script in my JADE template and so far I have: extends layout script. function collect_data() { var transitions = {}; $( ":checkbox:checked" ).each(function (index, element) { //// some code ...

The TS2583 error in TypeScript occurs when it cannot locate the name 'Set' within the code

Just started my Typescript journey today and encountered 11 errors when running tsc app.ts. Decided to tackle them one by one, starting with the first. I tried updating tsconfig.json but it seems like the issue lies within node_modules directory. Any help ...

Encountering issues following the integration of @angular/flex-layout into an Angular project

After careful consideration, I opted to utilize the responsive grid system provided by @angular/flex-layout instead of Bootstrap. By simply installing the npm package and adding it to my AppModule, I was able to integrate it seamlessly: import { NgModule ...

Is it possible for Angular to handle multiple routes for one path?

To create a landing page for anonymous users and an inbox for authenticated users without relying on manual navigation or path changes, I attempted to set up multiple components associated with the root path. However, my routing block did not work as plann ...

ReactJS state refuses to update

In my FreeCodeCamp leaderboard table, I have implemented functionality where clicking on the highlighted table header calls different URLs based on sorting criteria. The application either calls https://fcctop100.herokuapp.com/api/fccusers/top/recent or ht ...

Incorporate highcharts data into your Laravel project using the power of AJAX

Encountering an issue with loading data for a Highcharts chart. The response from my controller provides the following data: [['Doctorado', 91.86],['Maestría', 6.98],['Licenciatura', 1.16]] Although the AJAX call is succes ...