Using Ionic 2 pipe to filter a dynamically changing list based on the name property

Q) What could be causing the error in my code's syntax?

I am attempting to filter a list of items by their name property. However, the following code is resulting in the error:

Cannot read property 'toLowerCase' of undefined

Please note: The variable query is initially set as an empty string when the page loads.

var query = "";

This is my template:

  <ion-card *ngFor="#item of (items | clientNameFilter:query)">
    <img [src]="getItemImage(item)" (click)="editItem(item)"/>
    <ion-card-content (click)="editItem(item)">
      <h2 class="card-title">{{item.name}}</h2>
      <p>{{item.address.name}}</p>
      <p>{{item.address.addressLine1}}</p>
      <p>{{item.address.town}}</p>
      <p>{{item.address.postcode}}</p>
    </ion-card-content>
  </ion-card>

Here is my filter logic:

import {Pipe, PipeTransform} from 'angular2/core';
import {Client} from '../interfaces/client';

@Pipe({
  name: 'clientNameFilter',
  pure: false
})
export class ClientNameFilterPipe implements PipeTransform {
  transform(query: string, clients: Client[]) {
    return clients.filter(client => 
        client.name.toLowerCase().indexOf(query) > -1
    );
  }
}

Answer №1

The order of the parameters is incorrect and the second parameter should be an array:

@Pipe({
  name: 'clientNameFilter'
})
export class ClientNameFilterPipe implements PipeTransform {
  transform(clients: Client[], params: string[]) {
    let query = params[0];
    return clients.filter(client => 
        client.name.toLowerCase().indexOf(query) > -1
    );
  }
}

The first parameter represents the value or list where you want the pipe to be used, while the second parameter refers to your specific parameter(s).

For more information, please refer to this documentation:

Answer №2

Below is a modified version I created for handling contacts:

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

@Pipe({
  name: 'contactNameFilter'
})
export class ContactNameFilterPipe implements PipeTransform {
  transform(contacts: Array<any>, searchTerm: string) : Array<any> {
    if (contacts == null) {
      return [];
    }
    if (searchTerm == null) {
      return contacts;
    }
    return contacts.filter( contact => {
      return `${contact.firstName} ${contact.lastName}`.toLowerCase().indexOf(searchTerm) > -1;
    });
  }
}

Usage example:

<ion-item *ngFor="let contact of (contacts | async | contactNameFilter:searchTerm)">

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

Deactivate user input depending on a certain requirement

Greetings everyone, I am currently working with the following code snippet: <table class="details-table" *ngIf="peop && peopMetadata"> <tr *ngFor="let attribute of peopMetadata.Attributes"> <td class="details-property"&g ...

Using NestJS to inject a Factory provider into another Factory

I've gone through various questions here, but none of them addressed my issue: NestJS - Inject factory provider into another provider doesn't work I'm trying to set up an async provider that retrieves configurations from a remote repositor ...

I'm facing an issue with SSRProvider in my NextJs application

My application is developed using NextJs and Typescript, utilizing the react-bootstrap library for creating components. I am facing an issue where I keep receiving an error message stating that When server rendering, you must wrap your application in an &l ...

Accessing Properties or Methods in Angular2 Components

My application consists of 3 main components: PageMenu, LoginSession, and LoginForm. The purpose is to establish a connection between the variables in LoginSession and PageMenu, allowing for the proper functionality of the LoginForm component. PageMenu: ...

retrieve data from the server

Currently, I am delving into the world of Angular with ASP.NET Core 3.0 and still relatively new to it. Here's my scenario - I have a function that is able to save PDF files in a specific folder called "Resources\PdfFiles" within the ASP.NET back ...

What type of class is considered a mixin in programming?

Struggling to determine the type of a typescript mixin class without using a workaround method. Here are a couple of examples: type Constructor<T = {}> = new(...args: any[]) => T; function MyMixin<T extends Constructor>(BaseClass: T) { r ...

Steps for setting up an auth guard:1. Define a

I am facing an issue with implementing two guards in my Angular application. The first guard is supposed to restrict unauthorized users from accessing certain pages, while the second guard is meant to prevent authorized users from accessing the "sign-in" a ...

Using D3-GraphViz in Javascript along with an Angular template: A step-by-step guide

I am attempting to integrate d3-graphviz following the guidance provided here within an angular template, like in this example. The tutorial on the d3-graphviz website advises me to include the following code in the index.html file: <!DOCTYPE html> & ...

How to disregard the "Declaration not found" error while using VS Code with TypeScript

Working with Typescript and Vue Cli in VS Code, I encountered a "definition missing warning" at this particular line: import { setupCalendar, DatePicker } from "v-calendar"; The issue states: Could not find a declaration file for module 'v-calen ...

The getStaticProps() function in NextJS has not been invoked

Currently, I am working on a basic website and my goal is to retrieve data from an API and showcase it on my component. However, I've encountered an issue where the getStaticProps() method doesn't seem to be triggering. Below is the code snippet ...

Tips for applying attributes to an element in Angular 2

My Directive is a straightforward implementation with the following code: import { Directive, OnInit, OnDestroy, ElementRef } from "@angular/core"; @Directive({ selector: "[Checker]" }) export class Checker { constructor(private e: ElementRef) { ...

Transform the Object/String into a route query parameter string by hand

We have implemented query params in our Angular app to manage configuration settings that are subject to frequent changes. Currently, we are utilizing the following code snippet: this.router.navigate([], { relativeTo: this.activatedRoute, queryParams ...

Search for specific item within an array of objects

Working on an Angular project, I am attempting to remove an object from an array. To achieve this, I need to filter the array and then update the storage (specifically, capacitor/storage) with the modified array. Here is my function: deleteArticle(id: str ...

What is the best way to incorporate data from a foreach method into a function call within an HTML string?

Having trouble calling a function with data from a foreach loop while generating HTML cards and buttons from an array. The issue seems to be in the renderProducts() method. /// <reference path="coin.ts" /> /// <reference path="prod ...

Jest tests reveal potential errors indicating an object may be null

When running my Jest (typescript) test cases on mongoose Models, I encounter numerous errors such as: Error TS2531: Object is possibly 'null'. For example, consider the following code snippet where the error is reported on line 3: const user = ...

Ways to Close a Modal in Ionic 5

I have a scenario where I need to open a modal, perform an asynchronous action, and then automatically dismiss the modal once the action is completed. Specifically, I want to use the fetchData function to handle the async task. @Component({ }) export cla ...

"Implementing a loop to dynamically add elements in TypeScript

During the loop session, I am able to retrieve data but once outside the loop, I am unable to log it. fetchDetails(){ this.retrieveData().subscribe(data => { console.log(data); this.data = data; for (var k of this.data){ // conso ...

Differentiating response.data typing on the front end in Typescript depending on the request's success status

Consider this scenario: A secure API authentication route that I am not allowed to access for viewing or editing the code returns interface AuthSuccess { token: string user: object } on response.data if the email and password provided are correct, but ...

Unveiling the proper extension of component props to default HTML button props

Currently, I am in the process of developing a button component that includes a variant prop to specify its color scheme. Below is a simplified version of the code: interface Props extends React.HTMLProps<HTMLButtonElement> { variant: 'yellow ...

Oh no, an issue has occurred with The Angular Compiler! It appears that TypeScript version 3.9.10 was found instead of the required version, which should be >=3.6.4 and <

After upgrading my angular application from version 5 to version 9, I encountered an issue while trying to deploy my code on the server. ERROR in The Angular Compiler requires TypeScript >=3.6.4 and <3.9.0 but 3.9.10 was found instead. Even though ...