Angular2 Filtering Problem

Trying to create a filter in angular2, I have constructed an array of products as shown below:

private items = ["Apple", "Banana", "Orange"];

Below is the code for my filter pipe:

import {Pipe} from 'angular2/core';

@Pipe({name:'filter'})

export class FilterPipe {
    transform(value, args) {
        if(!args[0]){
            return value;
        }
        else if (value) {
            return value.filter(item => {
                for (let key in item){
                    if((typeof item[key]==='string' || item[key] instanceof String) && (item[key].indexOf(args[0]) !== -1)){
                        return true;
                    }
                }
            });
        }
    }
}

Incorporated an ul element in my component to display the products, along with an input element to facilitate filtering:

<input type="text" [(ngModel)]="filterInput">
                <ul>
                    <li *ngFor="#item of items | filter: filterInput">
                        {{item}}
                    </li>
                </ul>

The issue I am facing with this implementation is that the filter only works correctly when entering the first letter. Upon entering additional letters, the filter stops functioning properly. Any insights on how to resolve this?

Answer №1

Comparing each character of a string from an array with the input text is what you are attempting to do

'A'   => ('Apple') => 'A'.indexOf('A')   'p'.indexOf('A')   ...
'Ap'  => ('Apple') => 'A'.indexOf('Ap')  'p'.indexOf('Ap')  ... - always false
'App' => ('Apple') => 'A'.indexOf('App') 'p'.indexOf('App') ... - always false

The recommendation is to make changes to the pipe in this manner:

@Pipe({name:'filter'})   
export class FilterPipe {
  transform(value, args) {
    if(!args[0]) return value;   
    return value.filter(item => item.indexOf(args[0]) > -1);
  }
}

https://plnkr.co/edit/TpJ6Zu8QovWINqx04KUY?p=preview

!!! This pertains to Angular 2 Beta Version


In cases of the Angular RC version, the code will appear as follows:

@Pipe({ name: 'filter' })
export class FilterPipe {
  transform(value, term) {
    if (!term) return value;
    return value.filter(item => item.indexOf(term) > -1);
  }
}

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

Deciphering the JSON array generated by PHP

When PHP returns a JSON array, the output may look like this: [ { "uid": "1", "username": "mike", "time_created": "2014-12-27 15:30:03", "time_updated": "2014-12-27 15:30:03", "time_expires": "2014-12-27 15:30:03" }, { "uid": ...

Encountering a CORS issue while attempting to make a GET request to an API in an

Looking to retrieve HTML data from a website using an API. The target URL is: https://www.linkedin.com/ Trying to fetch the HTML page as text from this specific URL. Here's what I attempted: getData() { const api = "https://www.linkedin. ...

I am looking to trigger the change event from within the click event in Angular

My objective involves detecting when the cancel button is clicked while a file is being uploaded. I am trying to accomplish this by triggering the click event, then monitoring for the change event. If the change event occurs, the document will be uploaded. ...

Adjusting image dynamically based on conditions

I need to dynamically display images on my HTML based on specific conditions using TypeScript. In my TypeScript file: styleArray = ["Solitary", "Visual","Auditory","Logical","Physical","Social","Verbal",]; constructor(){ for (var i = 0; this.sty ...

Determine the sum of exported identifiers based on ESLint rules

Currently, I am facing a requirement in my JavaScript/TypeScript monorepo to ensure that each library maintains a minimal amount of exported identifiers. Is there any existing eslint rule or package available that can keep track of the total number of exp ...

What causes the appearance of the "?" symbol at the beginning of the URL and triggers a reboot of the app when moving through the absolute path?

I am facing an issue. In my multi-module application with lazy loading, I encountered a strange behavior when trying to navigate between child lazy modules. Transition from top module to bottom child module works fine, but routing from one bottom child la ...

The PUT method in the Node Express app is only functioning six times

I have set up my database with Mongodb to handle variable updates. Additionally, I am utilizing node.js along with an express server. Take a look at the code snippet below: router.route("/update/").put( async (req, res) =>{ const count_up ...

Continuous Updates to innerHtml in Angular2

While working on a project, I encountered an issue that seems to be more about style than anything else. The endpoint I am calling is returning an SVG image instead of the expected jpeg or png format, and I need to display it on the page. To address this, ...

Typescript monorepo facing issues with module resolution in Next.js projects

In my monorepo with yarn workspaces, I have 2 Next.js projects set up. apps ┣ app-1 ┗ app-2 The problem arises when app-1 needs to import components from app-2. I add app-2 as a dependency in the app-1 project and configure the path in app-1's ...

Designing functional components in React with personalized properties utilizing TypeScript and Material-UI

Looking for help on composing MyCustomButton with Button in Material-ui import React from "react"; import { Button, ButtonProps } from "@material-ui/core"; interface MyButtonProps { 'aria-label': string, // Adding aria-label as a required pro ...

Can TypeORM create an entity for a many-to-many relationship that functions like ActiveRecord's join table concept?

Consider a scenario where there is a Guardian entity connected to a Student entity. The goal is to establish their many-to-many relationship in TypeORM by introducing a new entity called StudentGuardianRelationship. This intermediary entity serves the purp ...

The Cypress executable cannot be located in the directory: /root/.cache/Cypress/3.8.3/Cypress/Cypress

Encountered an issue with the error message 'Cypress executable not found at: /root/.cache/Cypress/3.8.3/Cypress/Cypress' when running the cypress command 'npx cypress run -P projects/demoProject-cypress' on docker in the cloud environm ...

Retrieve information using an asynchronous pipeline once the screen is fully loaded

In my table component, I have integrated functionality for data reloading and filtering. These actions are powered by Subjects: private fetchFromServer$ = new Subject< void >(); private filter$ = new Subject< void >(); The data fetching proces ...

Transmitting a variety of content types in a single request

Is there a way to send multiple files along with extra JSON data to the API? I have noticed that the API is capable of handling various content types. I am wondering how I can create a header that includes two different content types: Multipart form data ...

Guide to accessing a menu through Long press or Right click in Angular2

I recently started experimenting with angular 2 and I am trying to figure out how to create a menu that opens with multiple options on both mobile and desktop devices. What I'm looking for is a way to trigger the opening of a menu when a long hold or ...

Securely connecting Angular front end with NodeJS backend server using HTTPS encryption

I am currently using a frontend built with Angular 7 and ngx-admin, along with a backend developed in nodeJS and Express. The issue: The Angular frontend uses HTTPS to communicate with the backend via HTTP. This has caused the following problem: Mixed Co ...

Transform JSON data that illustrates an array into an array of strings

There is an external string that represents a JSON array. Here's how it looks: ["abc", "xyz", "123"] The goal is to parse this into a String[] and then iterate over its elements. Currently, the code snippet outlines the intention of using the parse ...

When using setInterval, the image remains static on Safari but updates on Chrome

In my project, I am using a mock array to distribute data. One part of the project utilizes this data to display a list of cases, each with assigned images. When a case is hovered over, the images associated with that case are displayed one at a time, with ...

Setting a dynamically addressed property within a TypeScript interface

I have a situation where I need to dynamically access an object property using a variable that represents a keyof the object type. Here's an example: interface FidelityCheckRow { P1: number; P2: string; P3: string; } const keys: (keyof F ...

Retrieve a JSON array using an HTTP Get request in JavaScript (with jQuery)

I’ve been experimenting with various code snippets in an attempt to reach my objective, but so far I haven’t found a solution. Objective: My goal is to retrieve a JSON array of objects from a specific web URL using the GET method. This task needs to b ...