Having trouble getting my specialized pipe (filter) to function properly in Angular 2

I have implemented a custom pipe for filtering data in my table. Oddly, when I enter a search string into the input box, it correctly prints 'found' in the console but no rows are displayed in the table. However, if I remove the pipe altogether, all records show up as expected.

import { Component, Input, OnInit } from '@angular/core';
import { MyTableData } from '../interfaces/my-table-data.interface'

@Component({
    selector: 'my-table',
    template: `
    <div style="width: 100%">
        <div style="float: left; height: 50px; width: 100%">
            Search: <input type="text" [(ngModel)]="filterValue" style="height: 30px; border: 1px solid silver"/>
        </div>
        <div style="float: left; width: 100%">
            <table>
                <tr *ngFor="let row of data.rows | myTableFilter:filterValue">
                    <td *ngFor="let value of row">{{value}}</td>
                </tr>
            </table>
        </div>
    </div>
    `
})
export class MyTableComponent implements OnInit { 
    @Input() data: MyTableData;
    filterValue: string;

    ngOnInit() {

    }
}  

and pipe:

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

@Pipe({
    name: 'myTableFilter',
    pure: false
})
@Injectable()
export class MyTableFilterPipe implements PipeTransform {
    transform(items: any[], arg: string): any {
        if(arg == '') return true;

        items.filter(item => {
            for(let value of item) {
                if(String(value).indexOf(arg) !== -1) {   
                    console.log('found match') //it prints correctly
                    return true;
                }
            }
            return false;
        });
    };
}

Best regards

Answer №1

A pipe serves as a tool to modify input rather than act as a filter itself. In this scenario, the input being altered is the array data.rows, with the goal of displaying only rows that match a specific input parameter filterValue. The desired outcome is to return the array after it has been filtered, not simply a boolean value. It is essential to maintain the purity of the pipe, as it is designed to be purely functional and react only to changes in the input (such as the filterValue):

@Pipe({
    name: 'myTableFilter'
})
@Injectable()
export class MyTableFilterPipe implements PipeTransform {
    transform(items: any[], filterValue: string): any {
        if(!items) {
          return [];
        }
        if(!filterValue) {
          return items;
        }
        return items.filter(item => {
            for(let value of item) {
                if(String(value).indexOf(filterValue) !== -1) {   
                    return true;
                }
            }              
        });
    };
}

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

What is the best way to eliminate the alert message "autoprefixer: Greetings, time traveler. We are now in the era of CSS without prefixes" in Angular 11?

I am currently working with Angular version 11 and I have encountered a warning message that states: Module Warning (from ./node_modules/postcss-loader/dist/cjs.js): Warning "autoprefixer: Greetings, time traveler. We are now in the era of prefix-le ...

The best practices for utilizing ES6 Modules syntax in TypeScript files within a NextJS environment

The issue appears to be trapped in a loop: package.json is missing type: "module". This results in an error when trying to use modules in TypeScript files: An error occurred while running the seed command: /Users/me/code/me/prisma-learning/grap ...

Encountered a hiccup during the deployment of an Angular application on Heroku

I've been working on deploying an Angular app called "test-app" to Heroku via GitHub and everything seems to be going smoothly, except for setting up the express routing function. I've tried different paths, but Heroku keeps throwing this error: ...

Tips for getting Atom cucumber step jump package to function properly on a Windows operating system

Just recently, I installed the Atom text editor along with the cucumber-step package available at this link. However, after pressing CTRL+ALT+j, it failed to jump to the step implementation/definition. My operating system is Windows 10 and I am utilizing ...

Guidelines for crafting an intricate selector by utilizing mergeStyleSets and referencing a specific class

I'm currently in the process of developing a web application using ReactJS. In my project, I have the following code: const MyComponent = (props: { array: Array<Data> }) => { const styles = mergeStyleSets({ container: { ...

Is it possible to implement drag and drop functionality for uploading .ply, .stl, and .obj files in an angular application?

One problem I'm facing is uploading 3D models in angular, specifically files with the extensions .ply, .stl, and .obj. The ng2-upload plugin I'm currently using for drag'n'drop doesn't support these file types. When I upload a file ...

I am looking to enhance my array of objects by implementing a filter. It is important that the filter does not allow for duplicate checkboxes with the

My website : On the left-hand side of my webpage, there is a set of checkboxes with some repeated names that I don't want. For example, "Rice" is repeated twice but I only want it to display once. When checking the Rice checkbox, it should show all c ...

React: Issue accessing URL parameters using useParams() within a nested component

In my demo application, there are two components - QuoteDetail and Comments. Both require URL parameters, but I am only able to access them in the parent component. App.tsx: <Switch> // ... <Route path="/quotes" exact> <Al ...

What is the best way to associate a select dropdown with a form in Angular 2 using formBuilder

After conducting some research, I was surprised to find that the process is not as straightforward as I had expected. I have come across various methods using ngModel, such as Bind and fetch dropdown list value in typescript and Angular2, among others. Ho ...

Stop/continue a stopwatch Observable

I'm trying to create a basic stopwatch using angular/rxjs6. I've managed to start the timer, but I'm struggling with pausing and resuming it. source: Observable<number>; subscribe: Subscription; start() { this.source = tim ...

In Angular, I aim to invoke the this.addDispatchToReceive method whenever the outcome is successful within each forEach iteration

How can I ensure that the values from this.stockItemDispatch are obtained in this.addDispatchToReceive(); during each iteration of a loop, instead of only getting the last stock value? The issue is that the subscribe function runs after the foreach cycle ...

Resolving the Issue: How to Solve the "Missing Required Request Body" Error in Angular and Spring MVC

I'm encountering an issue with removing a product from the database using Angular on the frontend. The error message I am receiving is: Required request body is missing: public boolean prodcust.controller.DeleteController.deleteProduct(java.lang.Stri ...

Only the (click) event is functional in Angular, while the (blur), (focus), and (focusout) events are not functioning

I have a unique HTML element as shown below <div (hover)="onHover()" (double-click)="onDoubleClick()" (resize)="resize()" (dragend)="dragEnd()"> These 4 functions are designed to display information onHover ...

What steps should I take to resolve the error message "ESLint encountered an issue determining the plugin '@typescript-eslint' uniquely"?

Struggling to enable eslint linting in an ASP.NET Core MVC project that incorporates React.js and typescript? I'm facing a tough challenge trying to resolve the error mentioned above. In my setup, I'm using Visual Studio 2022 Community Edition 1 ...

Angular 2: The *ngFor directive is unable to locate a suitable differing framework

Below is the code for client.service.ts clients: Client[]; getClientList() { let headers = new Headers(); headers.append('Content-Type', 'application/json'); let authToken = localStorage.getItem('auth_token&apo ...

Testing the output of a directive in a component unit test by simulation

One of the features I implemented in my Angular 5 component is utilizing the typeahead directive from ngx-bootstrap. Here's a snippet of how it's integrated: <input [(ngModel)]="inputted" [typeahead]="days" (typeaheadOnSelect)="select($ ...

Is today within the current week? Utilizing Moment JS for time tracking

There is a problem that I am facing. Can you assist me in determining whether the day falls within the current week? I am currently developing a weather forecast service and need to validate if a given day is within the current week. The only clue I have ...

Accordion symbol for adding or subtracting

Looking for a way to change the Toggle text in my angular 7 application accordion to images or content displaying a + sign for collapse and - for expand. I need to achieve this using CSS in my SCSS stylesheet so that I can later change the color of the sig ...

The server failed to respond to the Angular HTTP request

To store data in my database, I have created a function in my component.ts file that invokes a service: ajoutText(newtext: String) { this.dataService.sendtext(newtext); } On the HTML side, it looks like this: <form class="form"> <mat-form-f ...

Struggling to retrieve the value of a text field in Angular with Typescript

In the Angular UI page, I have two types of requests that I need to fetch and pass to the app.component.ts file in order to make a REST client call through the HTML page. Request 1: Endpoint: (GET call) http://localhost:8081/api/products?productId=7e130 ...