Using an Angular 2 filter pipe to search across multiple values

Currently, I am working on implementing a filter for a table of users using pipes. While I have successfully made it work for filtering based on one selection, I am now attempting to extend this functionality to accommodate multiple selections. It's important to note that this is specifically for one column in the table. At the moment, the column contains names such as Adam, Brenda, Dan, Harry, and so on. Additionally, there may be multiple instances of the same name in the column, which should also be included in the filtered results. The pipe implementation I currently have looks like this:

import * as _ from 'lodash';
import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
name: 'dataFilter'
})
export class DataFilterPipe implements PipeTransform {

transform(array: any[], query: string): any {
if (query) {
  return _.filter(array, row=>row.user.indexOf(query) > -1);
}
return array;
}
}

My HTML code for using the pipe is simple:

<table [mfData]="tableData | dataFilter : filterQuery" #mf="mfDataTable">

In this snippet, the `filterQuery` variable represents just a string. But my goal is to pass an array of names into `filterQuery` to retrieve the values accordingly. For instance, if the user column has entries like:

  • Adam, Adam, Brenda, Dan, Harry, Harry, Harry

and I provide `filterQuery ['Adam' , 'Harry']`, I expect the output to be:

  • Adam, Adam, Harry, Harry, Harry

I would appreciate any guidance or suggestions on modifying the code to achieve this desired functionality! I have tried incorporating loops within the transform function using `query: string[]`, but haven't been successful so far.

Thank you!

Answer №1

I used this pipeline to accomplish my task:

export class DataFilterPipe implements PipeTransform {
transform(array[], query:string[]):any[] {
if (typeof array === 'object') {
  var resultArray = [];
  if (query.length === 0) {
    resultArray = array;
  }
  else {
    resultArray = (array.filter(function (a) {
      return ~this.indexOf(a.user);
    }, query));
  }
  return resultArray;
}
else {
  return null;
  }
 }
}

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

Tips for showing nested JSON data in a PrimeNG table within Angular version 7

I am struggling to display nested json data in a PrimeNG table. When I retrieve the data using an HTTP service, it appears as [object][object] when displayed directly in the table. What I want is to show the nested json data with keys and values separated ...

Using the index in Vue.js to locate a method within an HTML file

Currently, I am attempting to make use of the reference "index" located within <tr v-for="(note, index) in noteList" v-bind:key="index" in order to call shareToPublic(index). The method selectedID() allows for the selection of the ...

Implementing Firebase-triggered Push Notifications

Right now, I am working on an app that is built using IONIC 2 and Firebase. In my app, there is a main collection and I am curious to know if it’s doable to send push notifications to all users whenever a new item is added to the Firebase collection. I ...

Sporadic UnhandledPromiseRejectionWarning surfacing while utilizing sinon

Upon inspection, it appears that the objects failApiClient and explicitFailApiClient should be of the same type. When logging them, they seem to have identical outputs: console.log(failApiClient) // { getObjects: [Function: getObjects] } console.log(expli ...

What are the steps to create a dynamic navigation menu in Angular 2?

I have successfully implemented this design using vanilla CSS and JS, but I am encountering challenges when trying to replicate it in Angular 2. Setting aside routing concerns, here is the current state of my component: navbar.component.ts import { Comp ...

Combining promises to handle the asynchronous promise received from this.storage.get() function

Struggling with managing asynchronous data retrieval from local storage in my Angular2/ionic2 app. The code snippet I'm using: request(args) { var headers = new Headers(); headers.append('Content-Type', 'application/json&a ...

Creating QR codes from raw byte data in TypeScript and Angular

I have developed a basic web application that fetches codes from an endpoint and generates a key, which is then used to create a QR Code. The key is in the form of an Uint8Array that needs to be converted into a QR Code. I am utilizing the angularx-qrcode ...

Tips for creating a TypeScript function that can accept an array of concatenated modifiers with the correct data type

Can I modify data using a chain of function modifiers with correct typing in TypeScript? Is this achievable? const addA = (data: {}) => { return { ...data, a: "test" } } const addB = (data: {}) => { return { ...data, ...

The Action-Reducer Mapping feature is encountering a type error when handling multiple types of actions

Earlier today, I posed a question about creating a mapping between redux action types and reducers to handle each type explicitly. After receiving helpful guidance on how to create the mapping, I encountered an error when attempting to use it in creating ...

What are the pros and cons of defining `[defaultColor]="'violet'"` in Angular 2?

If you visit the advanced section of angular.io documentation, you will come across the following code snippet: <p [myHighlight]="color" [defaultColor]="'violet'"> Highlight me too! </p> It made me wonder, when binding to a consta ...

Ways to determine whether an element is presently engaged in scrolling

Is there a way to determine if certain actions can be disabled while an element is being scrolled? The scrolling may be triggered by using the mouse wheel or mouse pad, or by calling scrollIntoView(). Can we detect if an element is currently being scroll ...

Guide on displaying the length of an observable array in an Angular 2 template

I am working with an observable of type 'ICase' which retrieves data from a JSON file through a method in the service file. The template-service.ts file contains the following code: private _caseUrl = 'api/cases.json'; getCases(): Obs ...

Deciding Between Utilizing Observables or Promises in Angular

Having delved into Observables after transitioning from a predominantly Promise-based application, I recognize their effectiveness in handling streams and event patterns. However, I can't help but feel that there are instances where using Observables ...

I encountered a frustrating issue of receiving a 400 Bad Request error while attempting to install

I am currently in the process of installing Angular CLI using npm to incorporate Angular 4 into several projects. Unfortunately, I keep encountering a 400 Bad Request error. Has anyone else faced this issue before and found a solution? I have already searc ...

Dealing with Typescript Errors in Ionic3: How to Handle "Property 'x' does not exist on value of type 'y'" Issues

I stumbled upon this particular post (and also this one) while searching for a solution to my issue. I am looking to suppress these specific errors: 'Payload' property is missing from the 'Matatu' type. 'Key' property is no ...

The keys within a TypeScript partial object are defined with strict typing

Currently, I am utilizing Mui components along with TypeScript for creating a helper function that can generate extended variants. import { ButtonProps, ButtonPropsSizeOverrides } from "@mui/material"; declare module "@mui/material/Button&q ...

The scale line on the OpenLayers map displays the same metrics twice, even when the zoom level is different

When using the Openlayers Map scale line in Metric units, a specific zoom rate may be repeated twice during the zoom event, even though the actual zoom-in resolution varies on the map. In the provided link, you can observe that the zoom rates of 5km and ...

Limit pasted content in an Angular contenteditable div

Is there a way to limit the input in a contenteditable div? I am developing my own WYSIWYG editor and want to prevent users from pasting content from external websites and copying styles. I want to achieve the same effect as if the content was pasted into ...

Adjust the height, width, and color of the "kendo-switch" widget

I am looking to customize the height, width, and color of the "kendo-switch" component. I attempted to modify the element's style directly, but it did not have the desired effect. What would be the most effective approach for achieving this customiza ...

Updating the parent component upon navigating from the child component in Angular app

Struggling with updating the parent component after routing from a child component. Through research, I've learned that ngOnInit only runs once. Any way to work around this issue? I've experimented with different lifecycle hooks, but no luck so f ...