Giter VIP home page Giter VIP logo

ngx-filter-pipe's Introduction

Angular5+ Filter Pipe

downloads downloads npm version Greenkeeper badge PayPal donate button

Filter arrays

Angular 5+ pipeline for filtering arrays.

Demo Page

https://vadimdez.github.io/ngx-filter-pipe/

or see demo code

https://stackblitz.com/edit/ngx-filter-pipe

Usage

In HTML template
{{ collection | filterBy: searchTerm }}

Arguments

Param Type Details
collection array The collection to filter
searchTerm string or number or object or array or function Predicate used to filter items from collection

Install

npm install ngx-filter-pipe --save

For Angular lower than 5 use version 1.0.2

Setup

In case you're using SystemJS - see configuration here.

Usage

Import FilterPipeModule to your module

import { NgModule } from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent } from './app';
 
import { FilterPipeModule } from 'ngx-filter-pipe';
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [BrowserModule, FormsModule, FilterPipeModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

And use pipe in your component

import { Component } from '@angular/core';
 
@Component({
  selector: 'example-app',
  template: `
    <div>
        <input type="text" [(ngModel)]="userFilter.name" placeholder="name">
        <ul>
          <li *ngFor="let user of users | filterBy: userFilter">{{ user.name }}</li>
          
          <!-- in case you want to show empty message -->
          <li *ngIf="(users | filterBy: userFilter).length === 0">No matching elements</li>
        </ul>
    </div>  
  `
})
 
export class AppComponent {
  users: any[] = [{ name: 'John' }, { name: 'Jane' }, { name: 'Mario' }];
  userFilter: any = { name: '' };
}

$or matching

Use $or to filter by more then one values.

$or expects an Array.

In your component:

// your array
const languages = ['English', 'German', 'Russian', 'Italian', 'Ukrainian'];
// your $or filter
const filter = { $or: ['German', 'English'] };

In your template:

<div *ngFor="let language of languages | filterBy: filter">
  {{ language }}
</div>

Result will be:

<div>English</div>
<div>German</div>

$or example with nessted values

In your component:

// your array
const languages = [
  { language: 'English' },
  { language: 'German' },
  { language: 'Italian' }
];

// your $or filter
const filter = {
  language: {
    $or: ['Italian', 'English']
  }
};

In your template:

<div *ngFor="let object of languages | filterBy: filter">
  {{ object.language }}
</div>

Result:

<div>English</div>
<div>Italian</div>

$or example with multiple predicates

const objects = [
  { name: 'John' },
  { firstName: 'John' }
]

const filter = { $or: [{ name: 'John' }, { firstName: 'John' }] }

In your template:

<div *ngFor="let object of objects | filterBy: filter">
  {{ object | json }}
</div>

Result:

<div>{ name: 'John' }</div>
<div>{ firstName: 'John' }</div>

Use FilterPipe in a component

Inject FilterPipe into your component and use it:

class AppComponent {
  objects = [
    { name: 'John' },
    { name: 'Nick' },
    { name: 'Jane' }
  ];
  
  constructor(private filter: FilterPipe) {
    let result = this.filter.transform(this.objects, { name: 'J' });
    console.log(result); // [{ name: 'John' }, { name: 'Jane' }]
  }
}

Test

Run tests

npm test

Contribute

License

MIT ยฉ Vadym Yatsyuk

ngx-filter-pipe's People

Contributors

adamk33n3r avatar bigmassa avatar dependabot[bot] avatar greenkeeper[bot] avatar rubencodeforges avatar sameerbhat avatar studentivan avatar vadimdez avatar worldspawn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ngx-filter-pipe's Issues

strict string filter

Bug Report or Feature Request (mark with an x)
- [ ] Regression (a behavior that used to work and stopped working in a new release)
- [ ] Bug report -> please search issues before submitting
- [x] Feature request
- [ ] Documentation issue or request

is there an option to make string search strict (match the whole word)

Is it prosible to filter by two variable?

Like :-

<md-input-container>
  <input mdInput  placeholder="Enter name" [(ngModel)]="search">
</md-input-container> 
<md-card *ngFor = "let sectionDetails of section.value | filter:{'name':search,'code':search}" >
{{sectionDetails.name}}
{{sectionDetails.code}}
</md-card>

Please tell filter by list name and code but input field in one.

Filter fails when filter value is zero

In the code you check if there is no filter sent by !filter when the filter is number with value 0, the code assumes that there is no filter.

Solution:
use filter === undefined instead.

LowerCase error.

core.umd.js:2840 ORIGINAL EXCEPTION: value.toLowerCase is not a function ErrorHandler.handleError @ core.umd.js:2840 next @ core.umd.js:6424 schedulerFn @ core.umd.js:5722 SafeSubscriber.__tryOrUnsub @ Subscriber.ts:238 SafeSubscriber.next @ Subscriber.ts:190 Subscriber._next @ Subscriber.ts:135 Subscriber.next @ Subscriber.ts:95 Subject.next @ Subject.ts:61 EventEmitter.emit @ core.umd.js:5714 NgZone.triggerError @ core.umd.js:6018 onHandleError @ core.umd.js:5997 ZoneDelegate.handleError @ zone.js:246 Zone.runGuarded @ zone.js:129 NgZone.runGuarded @ core.umd.js:5871 outsideHandler @ platform-browser.umd.js:1829 ZoneDelegate.invokeTask @ zone.js:275 Zone.runTask @ zone.js:151 ZoneTask.invoke @ zone.js:345 core.umd.js:2843 ORIGINAL STACKTRACE: ErrorHandler.handleError @ core.umd.js:2843 next @ core.umd.js:6424 schedulerFn @ core.umd.js:5722 SafeSubscriber.__tryOrUnsub @ Subscriber.ts:238 SafeSubscriber.next @ Subscriber.ts:190 Subscriber._next @ Subscriber.ts:135 Subscriber.next @ Subscriber.ts:95 Subject.next @ Subject.ts:61 EventEmitter.emit @ core.umd.js:5714 NgZone.triggerError @ core.umd.js:6018 onHandleError @ core.umd.js:5997 ZoneDelegate.handleError @ zone.js:246 Zone.runGuarded @ zone.js:129 NgZone.runGuarded @ core.umd.js:5871 outsideHandler @ platform-browser.umd.js:1829 ZoneDelegate.invokeTask @ zone.js:275 Zone.runTask @ zone.js:151 ZoneTask.invoke @ zone.js:345 core.umd.js:2844 TypeError: value.toLowerCase is not a function at eval (http://localhost:5192/node_modules/ng2-filter-pipe/dist/src/ng2-filter.pipe.js:12:37) at Array.filter (native)

Filter by anything

Thanks for your work on this library. I have some user data already loaded in the view, and I'd like to filter by anything that matches. Do I have to specify each field in a getUsers() style function from your examples, or can it just look at the whole record and return anything that matches.

Here's some example code.

"users":[
      {
         "id":1,
         "email":"[email protected]",
         "fname":"User",
         "lname":"One",
         "department":2,
         "custom_fields":[
            {
               "id":1,
               "value":"ABC Company"
            },
            {
               "id":2,
               "value":"Designer"
            }
         ]
      },
      {
         "id":2,
         "email":"[email protected]",
         "fname":"User",
         "lname":"Two",
         "department":3,
         "custom_fields":[
            {
               "id":1,
               "value":"ABC Company"
            },
            {
               "id":2,
               "value":"President"
            }
         ]
      }
   ]
<input [(ngModel)]="searchTerm" value="searchTerm"></input>
<div *ngFor="let user of users | filterBy:searchTerm">

ObjectFiltering

Vadim, could you please show us how to use ng2-filter-pipe for object filtering.
Say [{'surname':'reeves', 'firstname':'keanu'}] filter by firstname?

Filtering by number within string

Bug Report or Feature Request (mark with an x)
- [x] Bug report -> please search issues before submitting

Hello,

I'm unable to filter by a number within a string.
Please have a look at this example: https://stackblitz.com/edit/angular-uwzg3w

E.g. when filtering by '2' I would like to get "item 2", "item 12" and "item 20" to "item 25".
How can i solve this task?

If the number is preceded by a matching sequence of characters the filter works just fine.

Thank you!

Demo page not loading

https://vadimdez.github.io/ng2-filter-pipe/

GET https://vadimdez.github.io/styles.df18ecbbddc27c2328d15607366a0475.bundle.css 404 (Not Found)
GET https://vadimdez.github.io/inline.d41d8cd98f00b204e980.bundle.js 404 (Not Found)
GET https://vadimdez.github.io/styles.b2328beb0372c051d06d.bundle.js 404 (Not Found)
GET https://vadimdez.github.io/main.562fd284a41b5c1276b5.bundle.js 404 (Not Found)

How to call filterPipe transform from Component ?

Hi,
Can you please advise how do we call FilterPipe transform from Component file ? When I am calling as below, it's throwing an error that "Property 'FilterPipe' does not exist on type 'FilterPipeModule'". Can you please advise ?

FilterPipeModule.prototype.FilterPipe

How to refresh the arrays?

In use is the latest verison of Angular (5.2.0) and the latest version of ngx-filter-pipe (2.1.0)
I use ngx-translate to load my language texts. When i load the site all works fine with the filter... But when i change the language ngx-filter-pipe still got the old language array in cache. How can i fix this?

How to filter by two variables of the same array

Hey guys,

In my use case I have the following object:

{
  "name": 'product 1';
  "version": '1';
  "software": null;
  "availability": ['Europe', 'America'];
  "language": ['English', 'German'];
}

I'm using objects with getters, binding as shown in the examples and returning the getter:

  constructor(data?: ProductInterface) {
    Object.assign(this, data);

    this.getName = this.getName.bind(this);
    this.getVersion = this.getVersion.bind(this);
    this.getLanguage = this.getLanguage.bind(this);
  }

  getLanguage() {
    return this.language;
  }

Currently to filter by one language I'd pass in the following filter:

{language: 'English'}

This works as intended, my issue is, I have a checkbox which allows the users to select multiple filters, how would I be able to pass both english and german into the language filter?

Server Side search Filter

does the module capable on Server Side Filtering.

if yes, is there any sample that i will be my reference

thanks in advance

Change detection not firing with object

I am using the pipe very similarly to the example given with ngx-filter-pipe v2.0.0 and angular v5.2.5.

Template:

<input type="text" placeholder="Find by name" [(ngModel)]="targetFiltersFilter.name">

<mat-chip-list>
  <mat-chip *ngFor="let target of targetFilters | filterBy: targetFiltersFilter">{{ target.name }}</mat-chip>
</mat-chip-list>

Inside component:

targetFilters: any[] = [{ name: 'aaaa' , selected: false },  { name: 'bbbb', selected: false }, ... ];
targetFiltersFilter: any = { name: '' };

It seems that the pipe isn't being triggered when I type into the input. I can see that the pipe gets triggered once when the page first loads but not at all after that when I modify targetFilterFilter's name attribute via the text field. The pipe does get fired, however, if I change its input to a string value instead of an object, or if I change pure: false in the pipe declaration. This says to me that Angular is doing some type of too shallow comparison for its change detection that doesn't take into account if an object's properties have been modified. Any advice? Would some change within a recent version of angular itself cause this?

Bug Report or Feature Request (mark with an x)
- [ ] Regression (a behavior that used to work and stopped working in a new release)
- [x] Bug report -> please search issues before submitting
- [ ] Feature request
- [ ] Documentation issue or request

Ngx-filter-pipe giving build error in Angular 4

Am using angular-cli with version 1.6.8 and Angular with version 4.0.0. After the installation of ngx-filter-pipe, the ng build is giving the below mentioned error

ERROR in ./src/main.ts
Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in 'C:\Harikrishnan_UI\VHealth\web\src'
resolve './$$_gendir/app/app.module.ngfactory' in 'C:\Harikrishnan_UI\VHealth\web\src'
using description file: C:\Harikrishnan_UI\VHealth\web\package.json (relative path: ./src)
Field 'browser' doesn't contain a valid alias configuration
after using description file: C:\Harikrishnan_UI\VHealth\web\package.json (relative path: ./src)
using description file: C:\Harikrishnan_UI\VHealth\web\package.json (relative path: ./src/$$_gendir/app/app.module.ngfactory)
no extension
Field 'browser' doesn't contain a valid alias configuration
C:\Harikrishnan_UI\VHealth\web\src$$_gendir\app\app.module.ngfactory doesn't exist
.ts
Field 'browser' doesn't contain a valid alias configuration
C:\Harikrishnan_UI\VHealth\web\src$$_gendir\app\app.module.ngfactory.ts doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
C:\Harikrishnan_UI\VHealth\web\src$$_gendir\app\app.module.ngfactory.js doesn't exist
as directory
C:\Harikrishnan_UI\VHealth\web\src$$_gendir\app\app.module.ngfactory doesn't exist
[C:\Harikrishnan_UI\VHealth\web\src$$_gendir\app\app.module.ngfactory]
[C:\Harikrishnan_UI\VHealth\web\src$$_gendir\app\app.module.ngfactory.ts]
[C:\Harikrishnan_UI\VHealth\web\src$$_gendir\app\app.module.ngfactory.js]
[C:\Harikrishnan_UI\VHealth\web\src$$_gendir\app\app.module.ngfactory]
@ ./src/main.ts 3:0-74
@ multi ./src/main.ts
ERROR in Error: Metadata version mismatch for module C:/Harikrishnan_UI/VHealth/web/node_modules/ngx-filter-pipe/ngx-filter-pipe.d.ts, found version 4, expected 3
at StaticSymbolResolver.getModuleMetadata (C:\Harikrishnan_UI\VHealth\web\node_modules@angular\compiler\bundles\compiler.umd.js:25616:34)
at StaticSymbolResolver._createSymbolsOf (C:\Harikrishnan_UI\VHealth\web\node_modules@angular\compiler\bundles\compiler.umd.js:25404:46)
at StaticSymbolResolver.getSymbolsOf (C:\Harikrishnan_UI\VHealth\web\node_modules@angular\compiler\bundles\compiler.umd.js:25385:14)
at C:\Harikrishnan_UI\VHealth\web\node_modules@angular\compiler\bundles\compiler.umd.js:24241:30
at Array.forEach ()
at extractProgramSymbols (C:\Harikrishnan_UI\VHealth\web\node_modules@angular\compiler\bundles\compiler.umd.js:24240:79)
at AotCompiler.analyzeModulesAsync (C:\Harikrishnan_UI\VHealth\web\node_modules@angular\compiler\bundles\compiler.umd.js:23796:47)
at CodeGenerator.codegen (C:\Harikrishnan_UI\VHealth\web\node_modules@angular\compiler-cli\src\codegen.js:32:14)
at Function.NgTools_InternalApi_NG_2.codeGen (C:\Harikrishnan_UI\VHealth\web\node_modules@angular\compiler-cli\src\ngtools_api.js:73:30)
at _donePromise.Promise.resolve.then (C:\Harikrishnan_UI\VHealth\web\node_modules@ngtools\webpack\src\plugin.js:428:58)
at

Filter on a object property which has space

@VadimDez , How I can use the filterBy on a object property which has space.

Like, I want to filter on user name, where user name has space.

Example: I have a user 'John Writer'. If I filter with 'John' it is working fine. But if I filter with 'John W' then nothing is coming.

Filter by array property

I am trying to filter object with array property like this:

{ listName: "list1", users : [{name: "John", surname: "Riddle"}, {name: "Mark", surname: "Spancer"}]

It is possible to filter object by user property? I was trying something like this but it doesnt work

filterList = { users: {name: '' }}

Filter by property/method on prototype chain

Hi,

im trying to filter by a property and I always get no results.

export class Place{
  id: number;
  name: string;
  shortDescription: string;

  get displayName(): string {
    return `${this.name} ${this.shortDescription}`;
  }
}

elsewhere

displayNameFilter: any = { displayName: '' };
nameFilter: any = { name: '' };

When i use

<div *ngFor="let place of placeList | filterBy: displayNameFilter" class="staff-assignments-columns">

I get no results, when i use:

<div *ngFor="let place of placeList | filterBy: nameFilter" class="staff-assignments-columns">

I get results. The only real difference is name is a field and displayName is a property.

Unexpected module 'Ng2FilterPipeModule' declared by the module 'AppModule'

While including the module in App module generate this error on bootstrapping the application:

    at SyntaxError.BaseError [as constructor] (http://localhost:4200/vendor.bundle.js:90821:27) [<root>]
    at new SyntaxError (http://localhost:4200/vendor.bundle.js:6643:16) [<root>]
    at http://localhost:4200/vendor.bundle.js:20597:40 [<root>]
    at Array.forEach (native) [<root>]
    at CompileMetadataResolver.getNgModuleMetadata (http://localhost:4200/vendor.bundle.js:20579:54) [<root>]
    at JitCompiler._loadModules (http://localhost:4200/vendor.bundle.js:60779:64) [<root>]
    at JitCompiler._compileModuleAndComponents (http://localhost:4200/vendor.bundle.js:60739:52) [<root>]
    at JitCompiler.compileModuleAsync (http://localhost:4200/vendor.bundle.js:60705:21) [<root>]
    at PlatformRef_._bootstrapModuleWithZone (http://localhost:4200/vendor.bundle.js:44409:25) [<root>]
    at PlatformRef_.bootstrapModule (http://localhost:4200/vendor.bundle.js:44384:21) [<root>]
    at Object.630 (http://localhost:4200/main.bundle.js:595:124) [<root>]
    at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30) [<root>]
    at Object.1098 (http://localhost:4200/main.bundle.js:119:18) [<root>]
    at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30) [<root>]````

On click anywhere gives an parse error(Error: Syntax error)

I have added the filter module. It is working fine . But giving a console error when click on anywhere on filter item shows in html view.

I am sharing the full console error please look into it.

Uncaught Error: Syntax error, unrecognized expression: #
at Function.Sizzle.error (scripts.bundle.js:1541)
at Sizzle.tokenize (scripts.bundle.js:2193)
at Sizzle.select (scripts.bundle.js:2620)
at Function.Sizzle [as find] (scripts.bundle.js:845)
at jQuery.fn.init.find (scripts.bundle.js:2873)
at new jQuery.fn.init (scripts.bundle.js:2983)
at jQuery (scripts.bundle.js:139)
at Function.e._getParentFromElement (scripts.bundle.js:13788)
at HTMLDocument.e._clearMenus (scripts.bundle.js:13788)
at HTMLDocument.dispatch (scripts.bundle.js:5183)

Can't filter by a boolean field

I can't use the filter for boolean properties ... having this list:

[ { "Id": 1, "Name": "makes the area safer", "Selected": true }, { "Id": 2, "Name": "makes the area greener", "Selected": false }, { "Id": 3, "Name": "makes the area more attractive", "Selected": true } ]

And then trying to get in the markup:
{{ (ImpactList | filterBy: { Selected: false })}}

It always return the whole list, the filter is not applied when using bools ...

Installation issues

Hi

Unfortunately I couldn't install this dependency, even if I run install it under root(npm install ng2-filter-pipe --save). I always get this error. Please advise.

16584 verbose stack Error: EPERM: operation not permitted, rename 'D:\angular\node_modules\json3' -> 'D:\angular\node_modules.json3.DELETE'
16585 verbose cwd D:\angular
16586 verbose Windows_NT 6.1.7601
16587 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Users\user_admin\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js" "install" "ng2-filter-pipe" "--save"
16588 verbose node v7.9.0
16589 verbose npm v5.3.0
16590 error path D:\angular\node_modules\json3
16591 error code EPERM
16592 error errno -4048
16593 error syscall rename
16594 error Error: EPERM: operation not permitted, rename 'D:\angular\node_modules\json3' -> 'D:\angular\node_modules.json3.DELETE'
16594 error { Error: EPERM: operation not permitted, rename 'D:\angular\node_modules\json3' -> 'D:\angular\node_modules.json3.DELETE'
16594 error cause:
16594 error { Error: EPERM: operation not permitted, rename 'D:\angular\node_modules\json3' -> 'D:\angular\node_modules.json3.DELETE'
16594 error errno: -4048,
16594 error code: 'EPERM',
16594 error syscall: 'rename',
16594 error path: 'D:\angular\node_modules\json3',
16594 error dest: 'D:\angular\node_modules\.json3.DELETE' },

Can't filter by getter properties of classes

If I have:

export class Painting {
   id;
   name;
   artist;
   city;

   get searchText() { return this.name + " " + this.artist + " " + this.city; }
}

I then populate the filter object:
let paintingFilter = {searchText: "atlanta"}

Then I apply the filter:
*ngFor="let painting of paintings | filterBy:paintingFilter

it will not search the getter property. Basically, I want to make the filter work on all properties of the object. Is this possible?

Filter a list of objects

Hello, suppose I have a list of objects in an *NgFor loop, and I want to filter by a property of one of those objects (e.g. the object is 'person' and it has a property 'name') - could I do that with this plugin? What about filtering by multiple properties?

Test when null is passed

Bug Report or Feature Request (mark with an x)
- [x] Regression (a behavior that used to work and stopped working in a new release)
- [ ] Bug report -> please search issues before submitting
- [ ] Feature request
- [ ] Documentation issue or request

Filtered set size

Great solution, works effectively.
However, is there a way to get a handle on the filtered set? Like getting the size of filtered items, or any other property?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.