Giter Site home page Giter Site logo

vadimdez / ngx-order-pipe Goto Github PK

View Code? Open in Web Editor NEW
243.0 11.0 58.0 8.01 MB

▼ Angular 5+ orderBy pipe

Home Page: https://vadimdez.github.io/ngx-order-pipe/

License: MIT License

TypeScript 79.65% JavaScript 5.76% HTML 12.40% SCSS 2.19%
order pipe angular4 angular5

ngx-order-pipe's Introduction

Angular 5+ Order Pipe

downloads downloads downloads

Order your collection by a field

Demo page

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

or see code example

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

Install

npm install ngx-order-pipe --save

For Angular lower than 5 use version 1.1.3

Setup

In case you're using systemjs - see configuration here. Otherwise skip this part.

Usage

In HTML template
{{ collection | orderBy: expression : reverse : caseInsensitive : comparator }}

Arguments

Param Type Default Value Details
collection array or object The collection or object to sort
expression string or string array The key or collection of keys to determinate order
reverse (optional) boolean false Reverse sorting order
caseInsensitive (optional) boolean false Case insensitive compare for sorting
comparator (optional) Function Custom comparator function to determine order of value pairs. Example: (a, b) => { return a > b ? 1 : -1; } See how to use comparator

Import OrderModule to your module

import { NgModule } from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent } from './app';

import { OrderModule } from 'ngx-order-pipe';

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

And use pipe in your component

import { Component } from '@angular/core';

@Component({
  selector: 'example',
  template: `
    <ul>
      <li *ngFor="let item of array | orderBy: order">
        {{ item.name }}
      </li>
    </ul> 
  `
})

export class AppComponent {
  array: any[] = [{ name: 'John'} , { name: 'Mary' }, { name: 'Adam' }];
  order: string = 'name';
}

Deep sorting

Use dot separated path for deep properties when passing object.

<div>{{ { prop: { list: [3, 2, 1] } } | orderBy: 'prop.list' | json }}</div>

Result:

<div>{ prop: { list: [1, 2, 3] } }</div>

Use OrderPipe in the component

Import OrderPipe to your component:

import { OrderPipe } from 'ngx-order-pipe';

Add OrderPipe to the constructor of your component and you're ready to use it:

constructor(private orderPipe: OrderPipe) {
  console.log(this.orderPipe.transform(this.array, this.order)); // both this.array and this.order are from above example AppComponent
}

Case insensitive / Case sensitive

Case insensitive flag is the third parameter passed to the pipe. Can be true to make comparison case insensitive and false to make comparison case sensitive. By default value is set to false.

  • Make case insensitive order (Third parameter is true)
<li *ngFor="let item of array | orderBy: order : false : true">
  {{ item.name }}
</li>
  • Switching third parameter to false will do case sensitive comparison to order collection:
<li *ngFor="let item of array | orderBy: order : false : false">
  {{ item.name }}
</li>

Donation

If this project help you reduce time to develop, you can give me a cup of tea :)

paypal

License

MIT © Vadym Yatsyuk

ngx-order-pipe's People

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  avatar  avatar  avatar

ngx-order-pipe's Issues

Order does not work for Date

Hi VadimDez,

Thank you so much for this awesome tool.

I am using Angular 5.2.0 and ngx-order-pipe: 2.0.1

The sort does not work for date

My displayed date is like below:
{{ testDate | date:'d MMMM yyyy' }}

The real date format in JSON is like this: Tue Mar 20 14:15:23 MDT 2018

Can you please help?
Thank you.

Issue with sorter

I have a date coming back in Long form.
Like "1489069644" which is equal to "Thursday, March 9, 2017 2:27:24 PM" if converted.

When I sort on this, it gets stuck and is constantly trying to sort and resort in random orders.

I am using this sort in other places, but never had an issue like this before. Do you know why its behaving this way?

These images were captured seconds apart. Its just constantly changing. (I am converting them when displaying) '{{note?.timestamp * 1000 | date:'MM/dd/yyyy hh:mm a'}}'

image

image

orderBy not found

Hi VadimDez,

Thanks for this tool.

I tried your steps mentioned using version "ngx-order-pipe": "^2.0.1".
also included the module as mentioned, but I get this error-
The orderBy in component.html is not found.

When I use the OrderPipe in component.ts it works and I am able to sort using the line-
this.notifications = this.orderPipe.transform(data, 'title')

only when i use it as -

it says orderBy could not be found.

It seems the html could not find orderPipe module. I also tried importing OrderPipe into main module,
but that didn't work too !

Thanks,
Mitesh

how to use comparator?

i have opened issue: #34
and given solution to use comparator so how can use it?can you give me real time example?
Thanx in advance

No provider for OrderPipe when using it in a component

I'm getting the following error in the console when I use the OrderPipe in my component:

Uncaught (in promise): Error: StaticInjectorError(AppModule)[CategoryListComponent -> OrderPipe]:
StaticInjectorError(Platform: core)[CategoryListComponent -> OrderPipe]:
NullInjectorError: No provider for OrderPipe!
Error: StaticInjectorError(AppModule)[CategoryListComponent -> OrderPipe]:
StaticInjectorError(Platform: core)[CategoryListComponent -> OrderPipe]:
NullInjectorError: No provider for OrderPipe!

I have imported the OrderPipe into the component like this:

import { OrderPipe } from 'ngx-order-pipe';

And injected it in the constructor like this:

constructor(private orderPipe: OrderPipe) { }

The OrderModule has been imported into the app-module.ts like so:

import { OrderModule } from 'ngx-order-pipe';

And it has been listed as an import in the @NgModule like thus:

imports: [ OrderModule]

I'm using angular 5.6.0 and ngx-order-pipe 1.1.3.

Any thoughts?

does not support deep properties

it will not work on complex objects such as

var testObj = {
  a: 'b',
  'hyph"en': 10,
  "hy[ph]en": 11,
  b: {
    c: [1, 2, 3],
    d: ['h', 'ch'],
    e: [{}, {f: 'g'}],
    f: 'i'
  }
};

expressions such as 'b.c[0]' or b.e[2].f would fail

I've tried to add tests and run them on my fork but couldn't get it to work, or spend more time on it. so i fixed it on my project by adding lodash, this is what my pipe looks like now:

import { Pipe, PipeTransform } from '@angular/core';
import * as lodash from 'lodash';
declare var _: any;
_ = lodash;

@Pipe({
  name: 'orderBy'
})
export class OrderPipe implements PipeTransform {

    transform(value: any[], prop?: any, reverse?: boolean, option?: string): any {

      if (!value) {
        return value;
      }

      let array: any[] = value.sort((a: any, b: any): number => {
        let aa = _.get(a, prop);
        let bb = _.get(b, prop);
        if (option && option.localeCompare('case-insensitive')==0 &&
            this.isString(aa) && this.isString(bb)) {
          return aa.localeCompare(bb);
        }
        return aa > bb ? 1 : -1;
      });

      if (reverse) {
        return array.reverse();
      }

      return array;
    }

    isString(value: any) {
      return typeof value === 'string' || value instanceof String;
    }
  }

Can not sort by embedded object value

I can't seem to sort by an embedded object value. For example, I am attempting to sort on something similar to customer.name like the following:

{
   customer: { name: "test" }
}

Table going crazy while using order pipe (same values mix)

Hi!

I'm using order pipe in my app. You can find it here -> http://gurustats.usermd.net/app/#/pgee17pary. When I scroll down this page, table is going crazy. I noticed that rows with the same values mixing with each other. How can i repair this?

Component:

import { Component, OnInit } from '@angular/core';
import { Pair } from "../interfaces/pair";
import { SpeedwayService } from '../../speedway.service';
import { OrderPipe } from 'ngx-order-pipe';

@Component({
  selector: 'gs-pgee2017pary-stats',
  templateUrl: './pgee2017pary-stats.component.html',
  styleUrls: ['./pgee2017pary-stats.component.less']
})
export class Pgee2017paryStatsComponent {
pgee2017pary: Array<any>;
order: string ='PLUSMINUS';
reverse: boolean = false;
result: number[];
  constructor(private _speedwayService: SpeedwayService,
    private orderPipe: OrderPipe) 
  {
    this._speedwayService.getPgee2017pary().subscribe((response) => {
    this.pgee2017pary = orderPipe.transform(response, 'PLUSMINUS');
   }
  )
  }
   setOrder(value: string) {
    if (this.order === value) {
      this.reverse = !this.reverse;
    }
    this.order = value;
  }
}


HTML:


<tr>
						<th [class.active]="order === 'PARA'"
							(click)="setOrder('PARA')">
							PARA<br>
							<span [hidden]="reverse">▼</span>
							<span [hidden]="!reverse">▲</span>
						</th>
						<th [class.active]="order === 'KLUB'"
							(click)="setOrder('KLUB')">
							KLUB<br>
							<span [hidden]="reverse">▼</span>
							<span [hidden]="!reverse">▲</span>
        				</th>
......

<tr *ngFor="let pair of pgee2017pary | orderBy: order: !reverse; let i = index">
......


The pipe 'orderBy' could not be found

First of all thank you for great work with pipe, I would love to use it, but I have an error "The pipe 'orderBy' could not be found". I've tried to do this with your ngx-order-pipe example, but it's not working. Order Module is imported in app.module.ts. My code:

html:

`<tr *ngFor="let rider of pgee2017 | orderBy: order; let i = index">`
<td> {{rider.MSC}} </td>
<td> {{rider.ZAWODNIK}} </td>
<td> {{rider.KLUB}} </td>

appComponent:

import { Component, OnInit } from '@angular/core';
import { Rider } from "../riders/rider";
import { Danepgee2017Service } from '../../danepgee2017.service';
import { OrderPipe } from 'ngx-order-pipe';

@Component({
  selector: 'gs-pgee2017-stats',
  templateUrl: './pgee2017-stats.component.html',
  styleUrls: ['./pgee2017-stats.component.less'],
})
export class Pgee2017StatsComponent {
pgee2017: Array<any>;
order: string ='msc';
reverse: boolean = false;
  constructor(private _danePgee2017Service: Danepgee2017Service,
    private orderPipe: OrderPipe) 
  {
    
  	this._danePgee2017Service.getPgee2017().subscribe(response => this.pgee2017 = response);
    console.log(this.orderPipe.transform(this._danePgee2017Service, this.order));
}

    setOrder(value: string) {
    if (this.order === value) {
      this.reverse = !this.reverse;
    }
    this.order = value;
}
}

I would be grateful for help. Cheers.

Multi Ordering?

Hello. Thanks for the pipe. It's been really usefull to me.

I want to ask if it is possible to order according to multiple values in order. For example first with Ages of people then the alphabetical order? If not, can you make it so? :)

Problem with reverse option but only with a version built with --env=prod

First, thanks for share your good job with this module, it's very useful.

I'm having a problem with the reverse true option only when the app is built with the --env=prod angular-cli flag. I had other problems with angular-cli with the --aot flag,

I have implemented a material extension panel and I'm using orderBy pipe in this way:

<mat-expansion-panel *ngFor="let purpose of purposes | async | searchPurposes:value | orderBy:'level':true"

In development version it runs ok, no problem. But, as I said, in --env=prod, when I toggle or click in the panel or anything that unleash to angular to compute the pipe, the problem is that the filtered items returned is different at any time that they are returned. If I switch the reverse: true to false, there is no problem (in any version).
I can't show at this moment any code because it's a "job work", when I will have time, I will try to do a version for you reproducing this problem. But I thought that maybe you will be interested to know if you have see other problems with the different kind of build versions with angular-cli.

Cannot find module, when server side building with Angular Universal / Platform Server

Hi,
when I'm launching my app with Angular Universal / Platform Server I get the following error:

Error: Cannot find module 'ngx-order-pipe'
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object. (/workdir/product-comperator/src/app/app.module.ts:21:1)
at Module._compile (module.js:571:32)
at Module.m._compile (/workdir/product-comperator/node_modules/ts-node/src/index.ts:392:23)
at Module._extensions..js (module.js:580:10)
at Object.require.extensions.(anonymous function) [as .ts] (/workdir/product-comperator/node_modules/ts-node/src/index.ts:395:12)
at Module.load (module.js:488:32)

this is the command that I use to launch the app with Universal:
ts-node --ignore=false src/server.ts

No errors are thrown when I launch my app with ng serve. The ngx-order-pipe is then working quite nicely.
Angular Universal has no problem finding the other third party module (ng2-nouislider) that I'm using in my project. It is stored in the node_modules directory as well. Therefore I'm not sure if the root of the problem is in my project or in the ngx-order-pipe code.

I'm importing the ngx-order-pipe in my app.module.ts file like so:
import { OrderModule } from 'ngx-order-pipe';
and this is how I'm importing the ng2-nouislider:
import { NouisliderModule } from 'ng2-nouislider';

Some more info about my environment:

angular/cli: 1.2.7
node: 7.10.1
os: linux x64
angular/animations: 4.3.3
angular/common: 4.3.3
angular/compiler: 4.3.3
angular/core: 4.3.3
angular/forms: 4.3.3
angular/http: 4.3.3
angular/platform-browser: 4.3.3
angular/platform-browser-dynamic: 4.3.3
angular/platform-server: 4.3.3
angular/router: 4.3.3
angular/cli: 1.2.7
angular/compiler-cli: 4.3.3
angular/language-service: 4.3.3

NPM: 4.2.0
[email protected]

Thanks for your help in advance!

Disable Sorting on a click

I am using angular5 and I am sorting an array of objects using ngx-order-pipe for a table data. But data is again sorting when clicking on the table row. how to disable the sorting with a click?

Error using reverse (ExpressionChangedAfterItHasBeenCheckedError)

<ion-card *ngFor="let team of gameProvider.game.teams | orderBy: 'team.points':true; let i = index">

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'Team 2'. Current value: 'Team 1'.

These values are in team.title. The content inside the html is empty, I'm not displaying anything yet

Data is flickering/jumping once loaded.

My data is jumping on the iniatial load , i have set order with defualt value. Then it worked but, when i click on some column name. Again values are flickering.

OrderBy boolean value

Hi!
I need to sort a data grid, but it contains a column which is filled with boolean value instead of strings or numbers. For now the data is being sorted like strings and false comes first when using the pipe, so for the time being I set up the column to be always reversed, but this is not the best approach, of course.
Is there any way to change the pipe to sort boolean values?

Sorting on multiple tables in same page

I would like to have sorting on multiple tables which are in same page. I tried to follow this documentation. When I'm sorting the table 1, table 2 is also getting sorted.How do I implement this on multiple tables separately. ?

order: any; reverse: boolean = false; setOrder(value: string) { if (this.order === value) { console.log(this.order) this.reverse = !this.reverse; } this.order = value; }

Table 1 :

Name Age
{{Data.name}} {{Data.age}}

Table 2 :

Id Sport
{{PersonData.id}} {{PersonData.sport}}

Clarification on deep property sorting.

It appears on the page a comma delimited list is specified but I can only see a period separated for the example. Either way I cannot seem to sort on a nested property. My code is

    <tr *ngFor="let loc of locationsPage | orderBy: order: reverse; let i = index">
                        <td>{{i + 1}}</td>
                        <td>{{loc.customer.customerName}}</td>
<th (click)="orderBy('customer.customerName')">Customer</th>

oderBy() sets the order key in the *ngFor

orderBy(order: string) {
        if (order === this.order) {
            this.reverse = !this.reverse;
        } else {
            this.order = order;
            this.reverse = false;
        }
    }

I have many nested properties in my table. I need to sort on a few of them. Is this possible using ng2-order-pipe? If so what is incorrect about my code above? Thank you for reading.

Order issue on load more items.

I am loading 30 items and i can sort it fine.
But if i am loading more 30 items into existance data without page reload then merged new data and old data should sort.
how i can re-init sort without page reload ?

reverse function

Im using AngularFire2 on my ionic2 project but reverse function not working.

experssion not found in build project

when i tape commande ng buil --prod

console raise an error like

ERROR in src\app\layout\setup\setup.component.html(23,54): : Property 'born_sup' does not exist on type 'SetupComponent'

but in env dev it works perfectly.

Cannot find module @angular/core

Adding it to an Angular CLI project, then importing in my shared module.

Building the project returns in:

ERROR in C:/projects/client/node_modules/ngx-order-pipe/dist/src/ngx-order.pipe.d.ts (1,31): Cannot find module '@angular/core'.

I'm on Angular 4.

Help for a newbie

Hi guys -
I'm trying to use the OrderBy Pipe - but I can't seem to get it installed.
If I clone the whole Git Repo - I can launch the demo app on my local system - no problem.

But when I try to include the Pipe in my own Angular App - I can't seem to get it installed correctly.

Here's what I've done:
I installed the ngx-order-pipe using npm ( and it's listed in my package.json file under: 'dependencies' : "ngx-order-pipe": "^2.0.1", )

I included the OrderModule in my AppModule - under imports

And the component in question has this import:
import { OrderPipe } from 'ngx-order-pipe';

My template has this line:

The error I'm getting (from the console) is:
compiler.js:466 Uncaught Error: Template parse errors:
The pipe 'orderBy' could not be found ("

-- I also tried including the OrderPipe as a Provider in the AppModule - but that didn't help either.
Help!

Any advice on what I'm missing or what else I should try would be greatly appreciated.
Thanks!

Null or undefined values

If target values are null or undefined, sorting becomes corrupt.
I have cloned your project and fixed it so it fits my use-case, where some values in rows might be null or undefined.
I just implemented a compare function as follows:
static compare(a: any, b: any ) {
if(a == null && b == null) return 0;
if(a != null && b == null) return -1;
if(a == null && b != null) return 1
return a > b ? 1 : -1;
}
And replaced some of the logic.
I also created som more tests to verify it.
Would you be intressted in me making a pull request?

The pipe 'orderBy' could not be found

My application is experiencing the following error: The pipe 'orderBy' could not be found

<ion-item *ngFor="let city of availableCities | orderBy: 'city.name'; let index_city = index">

Reordering during click

Hi,

I've implemented the ngx-order-pipe in angular 5 app where I am sorting the table on which rows are clickable to show more data and pipe is reordering the rows on click. May it be angular 5 compatibility issue/bug or I am doing something wrong?

`<ng-container *ngFor="let vdb of vdbs | orderBy: order">'

And my structure looks like that (clicking on row toogle the hidden table with multiple rows):

table
  row
    hidden table
  row
    hidden table

My sortable field is in main table rows

order: string = 'content.properties.DOMAIN.__text';

Can't find module

Can't find module:
ngx-order-pipe/dist/bundles/ngx-order-pipe (@1.1.1)

package.json is pointing to the wrong file

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.