Angular 2's filter pipe is not producing any results

I am facing an issue with using the filter pipe to filter my data as it is returning an empty page. Interestingly, when I remove the | filter from the HTML code, the data appears as expected. The filter pipe should display all names if the name exists.

This is my first time working with the filter pipe, so please let me know if there are any mistakes in the implementation.

Data Sample

[

    {
        "name": "Alien",
        "age": 18,
        "address": "lorem ipsum"
    },
    
    {
        "name": "Peter",
        "age": 17, 
        "address": "lorem ipsum"
    },
    
    {
        "name": "Ben",
        "age": 20, 
        "address": "lorem ipsum"
    }

HTML Code

<ion-item *ngFor="let list of this.data | filter: 'name'">
  
  <h2>{{ list.name }}</h2>
  
</ion-item>

Filter Pipe Logic

export class MyPipe implements PipeTransform {

transform(listArray: any, value: any): any {

if (value === undefined) return listArray;

for (let i = 0; i < listArray.length; i++) {
  
  if (listArray[i].indexOf(value) !== -1) {
      return value;
  }
  
}

}
  
}

Answer №1

When you write

listArray.indexOf("value")

The method will return the items that have exactly the string "value" inside the array.

I believe what you intended to use is

listArray.indexOf(value)

Answer №2

Before using your pipe, make sure to give it a name and use the 'value' attribute instead of just typing out 'value' as a string.

@Pipe({ name: 'customFilter' })
export class FilterPipe implements PipeTransform {
transform(inputArray: any[], searchValue: any): any[] {
if (searchValue === undefined) return inputArray;
for (let i = 0; i < inputArray.length; i++) {
if (inputArray.indexOf(searchValue)) {
return searchValue;
}
}
}
}

Answer №3

Here is how I approached the task:

filter.pipe.ts

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

@Pipe({
  name: 'filter'
})

export class FilterPipe implements PipeTransform {

  /**
   * The value parameter represents an array of servers
   */
  transform(value: any, filterString: string, propName: string): any {
    if(value.length === 0) {
      return value;
    }

    const resultArray = [];

    // Iterating through the items in the value array
    for(const item of value) {
      // Checking if the server status matches the filter criteria
      if(item[propName] === filterString) {
        resultArray.push(item);
      }
    }
    return resultArray;
  }
}

app.component.html

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <input type="text" [(ngModel)]="filteredStatus" class="form-control" placeholder="Filter by status">
      <hr>
      <ul class="list-group">
        <li
          class="list-group-item"
          *ngFor="let server of servers | filter: filteredStatus: 'status'"
          [ngClass]="getStatusClasses(server)">
          <span
            class="badge">
            {{ server.status }}
          </span>
          <strong>{{ server.name | shorten: 15 }}</strong> |
          {{ server.instanceType | uppercase }} |
          {{ server.started | date:'fullDate' | uppercase }}
        </li>
      </ul>
    </div>
  </div>
</div>

app.component.ts

  filteredStatus = '';

  appStatus = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('stable');
    }, 2000);
  });

  servers = [
    {
      instanceType: 'medium',
      name: 'Production',
      status: 'stable',
      started: new Date(15, 1, 2017)
    },
    {
      instanceType: 'large',
      name: 'User Database',
      status: 'stable',
      started: new Date(15, 1, 2017)
    },
    {
      instanceType: 'small',
      name: 'Development Server',
      status: 'offline',
      started: new Date(15, 1, 2017)
    },
    {
      instanceType: 'small',
      name: 'Testing Environment Server',
      status: 'stable',
      started: new Date(15, 1, 2017)
    }
  ];

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

Leverage the component's recursive capabilities to build a tree structure from within

Is it feasible to use a component within itself? If so, where can I find more information on this? I am facing the following scenario: I have a list of main items, each main item has a subitem (which looks like the main item), and each subitem can have i ...

Iterating over a JSON array using *ngFor

Here is the JSON structure that I have: { "first_name": "Peter", "surname": "Parker", "adresses": { "adress": [{ "info1": "intern", "info2": "bla1" }, { "info1": "extern", "info2": "bla2" }, { "info1": " ...

Ways to modify the color of mat-icon within an input field using Angular 6

Here is the code from my HTML file: <div class="input-field"> <div> <input type="text" id="name" required email/> <label for="name">Email: <mat-icon svgIcon="mail" class="change-color"></mat-icon> &l ...

What is the best way to set up JSData with cookie-based sessions and CSRF headers?

In order to properly configure my JSData settings, I must include instructions for passing information related to cookie-based session authentication and CSRF headers. ...

Leveraging the keyof keyword to access a specific property within a type

I have a variety of types that I need to work with. For example: type Type = { prop1: number; prop2: string; prop3: someOtherType } type Props = keyof Type I am aware that using an "indexed access type" allows me to extract the type of propN, ...

Tips for resolving the undefined error in TypeScript and React

Hey, I have this code snippet below which includes a call to the isSomeFunction method that returns true or false. However, there are times when the argument can be undefined. I only want to execute this function if selectedItems is not undefined. How can ...

Creating a global variable in Angular that can be accessed by multiple components is a useful technique

Is there a way to create a global boolean variable that can be used across multiple components without using a service? I also need to ensure that any changes made to the variable in one component are reflected in all other components. How can this be ac ...

SwitchMap in Typescript allows you to switch to a

In my TypeScript code, I have implemented multiple interfaces, components, and a key/interface map. interface FooProps { 'keyInFoo': string } const Foo = (props: FooProps) => {} interface BarProps { 'keyInBar': string } cons ...

Is there a way to load a JSON file into an Angular component using axios?

After generating an Angular 5 app using ng-cli, I created the following component: import {Component} from '@angular/core'; import axios from 'axios'; @Component({ selector: 'app-root', templateUrl: './app.component ...

Tips for utilizing ng class within a loop

Having some trouble with my template that loops through a JSON file using json server. The issue I'm facing is related to correctly applying ng class when clicking on icons. Currently, when I click on an icon, it adds a SCSS class but applies it to al ...

NgFor is failing to display data from a fully populated array of objects

CLICK HERE FOR THE IMAGE So, let's tackle the issue at hand. I have an array that contains data fetched from an API. These data points are essentially messages. Now, below is the TypeScript file for a component where I aim to display all these messag ...

Ways to import a library in JavaScript/TypeScript on a web browser?

I'm currently working on a project that involves a TypeScript file and an HTML page. Right now, I am loading the necessary libraries for the TypeScript file in the HTML Page using script tags like <script src="https://unpkg.com/<a href="/cd ...

Tips for implementing pagination in ag-Grid with Angular 2

Currently, I am working on developing a grid with pagination feature in Angular 2 using ag-grid. I have already attempted the code below in the HTML file: [gridOptions]="gridOptions" [columnDefs]="columnDefs" [showToolPan ...

Utilize generic types as object properties in TypeScript

Is there a way to achieve something similar in TypeScript like the following: export type CoordinateSelector = <T>(d: Coordinate) => d[T]; export interface LinkVerticalLineProps { x: CoordinateSelector<'x'>; y: CoordinateSele ...

No data found on Angular TypeScript page with an empty array

Incorporated a function called 'getQuestionsWithInterviewId' to populate my 'Questions' string, but it appears empty when I attempt to call it within the ngOnInit and ngAfterContentInit methods and log the result in the console. import ...

Utilize the canActivate method to decide when to display a specific hyperlink

I'm facing a challenge with my AuthGuard implementation using CanActivate to decide whether or not to display a link. Despite my efforts, I am unable to properly check the canActivate property of the Route. Here is the function I created: TypeScript ...

Adjust the clear button functionality within the ngx daterange picker

I am attempting to dynamically set the minDate and maxDate of my calendar. I have tried various methods to achieve this, however, I am looking to reset these values to null using the "Clear" button. In my .ts file, I have the following: startDateClicked($ ...

Having difficulty implementing a versatile helper using Typescript in a React application

Setting up a generic for a Text Input helper has been quite challenging for me. I encountered an error when the Helper is used (specifically on the e passed to props.handleChange) <TextInput hiddenLabel={true} name={`${id}-number`} labelText=" ...

Using Math.min() or Math.max() syntax in Angular templates: A comprehensive guide

Within my pagination module, the following code snippet can be found: <p>Displaying {{(page-1) * pageSize}} to {{ Math.min((page-1) * pageSize + pageSize,tasks.length)}} out of {{tasks.length}}</p>. Unfortunately, it seems to be experiencing ...

Tips for optimizing Angular source code to render HTML for better SEO performance

Our web platform utilizes Angular JS for the front-end and node js for the backend, creating dynamic pages. When inspecting the code by viewing the source, it appears like this: For our business to succeed, our website needs to be SEO-friendly in order to ...