Angular 2 Custom Pipe Magic

I'm brand new to using the Angular 2 framework and I'm attempting to create a custom filter.

app.component.ts

import {Component} from 'angular2/core';
import {HTTP_PROVIDERS} from 'angular2/http';

@Component({
    selector: 'my-app',
    providers: [UserService,HTTP_PROVIDERS],
    pipes: [SearchPipe],
    templateUrl : `app/user-template.component.html`,
    styles:[`
      .mt20 { margin-top: 20px; }
      .mt30 { margin-top: 30px; }
    `]    
})

export class AppComponent { 
  private users = [];
  onClick(searchStr){
    console.log("textbox value : ",searchStr.value);
  }
  constructor(private _userService : UserService){
        this._userService.getUsersData().subscribe(
            data => this.users = data
        );
  } 
}

HTML

<div class="row">
    <div class="col-md-4 col-md-offset-4 mt20">
        <div class="input-group">
            <input type="text" class="form-control" #searchStr>
            <span class="input-group-btn">
                    <button class="btn btn-default" type="button" (click)="onClick(searchStr)">Search</button>
            </span>
        </div>
    </div>
</div>
<hr>
<!--       Cards        -->
<div class="container mt30">
    <div class="row">
        <div class="col-md-3" *ngFor="#user of users | search : searchStr, #i=index">
            <div class="card" style="border: 1px solid black; padding:5px; text-align:center;border-radius:5px;">
                <div class="card-block">
                    <h4 class="card-title">{{user.name}}</h4>
                    <h6 class="card-title">{{user.email}}</h6>
                    <p class="card-text">{{user.company.catchPhrase}}</p>
                    <a href="#" class="btn btn-primary">Learn More</a>
                </div>
            </div>
            <div *ngIf="i == 3 || 6">
                <br/>
            </div>

        </div>
    </div>
</div>

Pipe

import {Pipe} from 'angular2/core';

@Pipe ({
    name : 'search',
    pure: false
})

export class SearchPipe {
    transform (value, args: any[]){
        return value.filter(
            (item) => { if(value.length > 0){
                    for(var i=0; i< value.length; i++){
                        if(value[i].name == args[0].value || value[i].email == args[0].value){
                            console.log("Filtered Object :",value[i]);
                            return value[i];
                        }else{
                            return;
                        }
                    }
                }
            });
    }
}

I'm experiencing an issue where the list is not loading initially when the page loads. When I try to search for a string (such as a name or email), the entire list is displayed. I'm unsure exactly what is happening. Can someone assist me?

Answer №1

filter function applies a specified function to all elements in an array and returns only those that satisfy the condition.

Your SearchPipe class should be structured as follows:

export class SearchPipe {
  transform (value: any[], args: any[]){
    const search = args[0].value;

    return value.filter(
      (item) => {
          if(item.name == search || item.email == search){
            console.log("Filtered Object :", item);
            return true
          }else{
            return false;
          }
      });
  }
}

Alternatively, you can use a shorter version like this:

export class SearchPipe {
  transform (value: any[], args: any[]){
    const search = args[0].value;

    return value.filter(item => 
      (item.name == search || item.email == search)
    );
  }
}

Avoid searching on empty strings with this modified version:

export class SearchPipe {
  transform (value: any[], args: any[]){
    const search = args[0].value;

    if (!search) return value;

    return value.filter(item => 
      (item.name == search || item.email == search)
    );
  }
}

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

Angular 2 update function in the MEAN Stack is not functioning as expected

I'm encountering a strange error that I can't seem to figure out. I've selected PUT on my postman and using route.put. Here's the error message I'm getting in Postman: Image link -> https://ibb.co/dzvAKc Looking at all the mus ...

System CSS modules do not work correctly with Reactjs, CRA, TS, and Carco when using Less

Issues have arisen with the CSS module system in my project. Below are snippets from various code files and configurations: react-app-env.d.ts, craco.config.js, CircleButtonWithMessage.module.less, CircleButtonWithMessage.tsx, as described below: //react-a ...

Using ngFor to display a default image

My latest project involved creating a table that displays various products along with their corresponding images. Everything was working smoothly until I encountered an issue. In instances where a product is created without an associated image, I decided ...

The directive subscription remains inactive even when the subject triggers the next function

Plunkr: https://plnkr.co/edit/KfPfVSbZm087uIPvFEkM?p=preview I have developed a service that serves as an API for a modal component. In addition, there is a directive available that can be used to apply a class to any element when the modal is open. Howev ...

Angular 2's Conditional Validation: A Comprehensive Guide

Angular 2 offers straightforward validation, which is a great feature. However, the challenge lies in making a required field optional based on another field's selection. Below are the validation rules: this.contractsFilter = this.fb.group({ selec ...

Tips for easily navigating Angular google Maps

<agm-map [zoom]="mapConfig.zoom" [styles]="mapConfig.styles" [latitude]="currLate" [longitude]="currLongi" > <agm-direction *ngIf="path" [origin]="path.origin" [destination]="path.destination" ...

Exploring deep nested components and elements in Angular for a targeted specific functionality

Is it possible to apply the ng deep css class to only one specific checkbox in my component, rather than all checkboxes? I want to customize just one checkbox and leave the others unchanged. How can this be achieved? Thank you. I need the CSS modificatio ...

How to efficiently upload multiple files simultaneously in Angular 10 and .NET Core 5 by utilizing a JSON object

I have a JSON object structured like this: Class->Students this is a basic representation of my TypeScript class export class Classroom { Id:number; Name:string; Students:Student[]=[]; } export class Student { Name:string; Age:number; Sex:string; Imag ...

Utilize *ngIf to conceal a row within a material table

I'm struggling with hiding a row after clicking a button in the mat-table. I can't figure out where to place the *ngIf directive. I attempted using it on ng-container, but it didn't work as expected. Below is the excerpt from my HTML file. ...

Nvm does not have the ability to generate an Angular project

Creating an Angular project using nvm has been a bit of a challenge for me. Here are the steps I took: D:\Project1>nvm list The output showed: 14.16.1 Next, I ran the following command. F:\Ashok\Angular\Angular>nvm use 14.16.1 ...

Angular 2+: The art of creating an instance of a class using data retrieved from the backend

Within my Angular app, I have a Customer class and an ICustomer interface. interface ICustomer { <-- obtained from backend id: number; name: string; address: string; // additional properties } class Customer { <-- widely used in th ...

What are the best techniques for centering a prime ng form both vertically and horizontally?

I am currently using prime ng 9.1.3 along with primeflex 1.3.0 in my project. Despite applying p-align-center, I am facing difficulty in vertically and horizontally centering the form on the screen when using a full screen height of 100vh. <div class=&q ...

Converting string literals to an array of enums

I have a scenario where I am getting the following data in an API response: { "roles": [ "ADMIN", "USER" ] } The response always includes an array of roles (USER, PRESENTER, ORGANIZER, and ADMIN). I am looking to transform this into a valid TypeScript a ...

The type 'string[]' is missing the required property 'label', resulting in a typescript error

Within my codebase, I've defined a type called Person that looks like this : type Person = { value?: string[]; label?: string[]; }; Additionally, there is a promise function in my project: async function main(): Promise<Person> { const fo ...

How come I'm seeing an extra addition being added to the string after I override it?

My objective is to call a function in a service from a component that will provide me with a string array. The first time I receive an array, everything seems fine. For example: http://localhost:4200/assets/images/hardwoods/american_white_oak.png However ...

The functionality of Angular 9 Service Worker appears to be inhibited when hosting the site from a S3 Static Website

I created a Progressive Web Application (PWA) following these steps: Started a new Angular app using CLI 9.1.8; Added PWA support by referring to the documentation at https://angular.io/guide/service-worker-getting-started; Built it with ng build --prod; ...

How to configure dynamic columns in material-table using React and TypeScript

My task involves handling a table with a variable number of columns that are generated dynamically based on the data received. To manage these columns, I have designed an interface that defines various properties for each column, such as whether it can be ...

When attempting to access the Angular app in Edge, it automatically redirects to open in IE 11 instead

I have encountered an issue with my angular 5 App. It works perfectly fine in Chrome and Firefox, but when I try to open it in Microsoft Edge on Windows 10, the application always opens in the IE 11 browser. There are no errors displayed on the console. W ...

Next.js experiencing hydration error due to dynamic component

Having an issue with my RandomShape component, where it should display a random SVG shape each time the page is reloaded. However, I am encountering a hydration error on the client side. import React from "react"; import shapes, { getRandomShape ...

Struggling to overcome the TS2322 error when assigning generic values

I am currently working on developing higher-order React components that will include default values for components labeled as "named". Here is a basic implementation example: type SomeProps = { a: string } type Variants = 'variantA' | 'var ...