Giter VIP home page Giter VIP logo

ngx-pagination's Introduction

Pagination for Angular Build Status

The simplest solution for pagination in Angular.

Table of Contents

Demo

Check out the live demo here: http://michaelbromley.github.io/ngx-pagination/

Play with it on StackBlitz here: https://stackblitz.com/edit/angular-e1f9hq

Quick Start

npm install ngx-pagination --save

Angular Version

This library is built to work with Angular 13+. If you need to support an earlier version of Angular, please use v5.x.

Simple Example

// app.module.ts
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {NgxPaginationModule} from 'ngx-pagination'; // <-- import the module
import {MyComponent} from './my.component';

@NgModule({
    imports: [BrowserModule, NgxPaginationModule], // <-- include it in your app module
    declarations: [MyComponent],
    bootstrap: [MyComponent]
})
export class MyAppModule {}
// my.component.ts
import {Component} from '@angular/core';

@Component({
    selector: 'my-component',
    template: `
    <ul>
      <li *ngFor="let item of collection | paginate: { itemsPerPage: 10, currentPage: p }"> ... </li>
    </ul>
               
    <pagination-controls (pageChange)="p = $event"></pagination-controls>
    `
})
export class MyComponent {
    p: number = 1;
    collection: any[] = someArrayOfThings;  
}

API

PaginatePipe

The PaginatePipe should be placed at the end of an NgFor expression. It accepts a single argument, an object conforming to the PaginationInstance interface. The following config options are available:

<some-element *ngFor="let item of collection | paginate: { id: 'foo',
                                                      itemsPerPage: pageSize,
                                                      currentPage: p,
                                                      totalItems: total }">...</some-element>
  • itemsPerPage [number] - required The number of items to display on each page.
  • currentPage [number] - required The current (active) page number.
  • id [string] If you need to support more than one instance of pagination at a time, set the id and ensure it matches the id attribute of the PaginationControlsComponent / PaginationControlsDirective (see below).
  • totalItems [number] The total number of items in the collection. Only useful when doing server-side paging, where the collection size is limited to a single page returned by the server API. For in-memory paging, this property should not be set, as it will be automatically set to the value of collection.length.

PaginationControlsComponent

This a default component for displaying pagination controls. It is implemented on top of the PaginationControlsDirective, and has a pre-set template and styles based on the Foundation 6 pagination component. If you require a more customised set of controls, you will need to use the PaginationControlsDirective and implement your own component.

<pagination-controls  id="some_id"
                      (pageChange)="pageChanged($event)"
                      (pageBoundsCorrection)="pageChanged($event)"
                      maxSize="9"
                      directionLinks="true"
                      autoHide="true"
                      responsive="true"
                      previousLabel="Previous"
                      nextLabel="Next"
                      screenReaderPaginationLabel="Pagination"
                      screenReaderPageLabel="page"
                      screenReaderCurrentLabel="You're on page">
</pagination-controls>
  • id [string] If you need to support more than one instance of pagination at a time, set the id and ensure it matches the id set in the PaginatePipe config.
  • pageChange [event handler] The expression specified will be invoked whenever the page changes via a click on one of the pagination controls. The $event argument will be the number of the new page. This should be used to update the value of the currentPage variable which was passed to the PaginatePipe.
  • pageBoundsCorrection [event handler] The expression specified will be invoked when the currentPage value is found to be out-of-bounds (e.g. the collection size was reduced). The $event argument will be the number of the closest valid page.
  • maxSize [number] Defines the maximum number of page links to display. Default is 7. Minimum is 5.
  • directionLinks [boolean] If set to false, the "previous" and "next" links will not be displayed. Default is true.
  • autoHide [boolean] If set to true, the pagination controls will not be displayed when all items in the collection fit onto the first page. Default is false.
  • responsive [boolean] If set to true, individual page links will not be displayed on small screens. Default is false.
  • previousLabel [string] The label displayed on the "previous" link.
  • nextLabel [string] The label displayed on the "next" link.
  • screenReaderPaginationLabel [string] The word for "Pagination" used to label the controls for screen readers.
  • screenReaderPageLabel [string] The word for "page" used in certain strings generated for screen readers, e.g. "Next page".
  • screenReaderCurrentLabel [string] The phrase indicating the current page for screen readers, e.g. "You're on page ".

PaginationControlsDirective

The PaginationControlsDirective is used to build components for controlling your pagination instances. The directive selector is pagination-template, either as an element or an attribute. It exports an API named "paginationApi", which can then be used to build the controls component.

It has the following inputs and outputs:

@Input() id: string;
@Input() maxSize: number;
@Output() pageChange: EventEmitter<number>;
@Output() pageBoundsCorrection: EventEmitter<number>;

Here is an example of how it would be used to build a custom component:

<pagination-template #p="paginationApi"
                     (pageChange)="pageChange.emit($event)"
                     (pageBoundsCorrection)="pageBoundsCorrection.emit($event)">

        <div class="pagination-previous" [class.disabled]="p.isFirstPage()">
            <a *ngIf="!p.isFirstPage()" (click)="p.previous()"> < </a>
        </div>

        <div *ngFor="let page of p.pages" [class.current]="p.getCurrent() === page.value">
            <a (click)="p.setCurrent(page.value)" *ngIf="p.getCurrent() !== page.value">
                <span>{{ page.label }}</span>
            </a>
            <div *ngIf="p.getCurrent() === page.value">
                <span>{{ page.label }}</span>
            </div>
        </div>

        <div class="pagination-next" [class.disabled]="p.isLastPage()">
            <a *ngIf="!p.isLastPage()" (click)="p.next()"> > </a>
        </div>
    
</pagination-template>

The key thing to note here is #p="paginationApi" - this provides a local variable, p (name it however you like), which can be used in the template to access the directive's API methods and properties, which are explained below:

  • pages [{ label: string, value: any }[]] Array of page objects containing the page number and label.
  • maxSize [number] Corresponds to the value of maxSize which is passed to the directive.
  • getCurrent() [() => number] Returns the current page number.
  • setCurrent(val) [(val: number) => void] Triggers the pageChange event with the page number passed as val.
  • previous() [() => void] Sets current page to previous, triggering the pageChange event.
  • next() [() => void] Sets current page to next, triggering the pageChange event.
  • isFirstPage() [() => boolean] Returns true if the current page is the first page.
  • isLastPage() [() => boolean] Returns true if the current page is the last page
  • getLastPage() [() => number] Returns the page number of the last page.
  • getTotalItems() [() => number] Returns the total number of items in the collection.

For a real-world implementation of a custom component, take a look at the source for the PaginationControlsComponent.

Styling

The PaginationControlsComponent can be styled by simply overriding the default styles. To overcome Angular's view encapsulation, you may need to use the ::ng-deep operator to target it (depending on the type of encapsulation your component is using).

To avoid specificity issues, just add your own custom class name to the element, which will allow your styles to override the defaults:

// head
<style>
  .my-pagination ::ng-deep .ngx-pagination .current {
    background: red;
  }
</style>

// body
<pagination-controls class="my-pagination"><pagination-controls>

Server-Side Paging

In many cases - for example when working with very large data-sets - we do not want to work with the full collection in memory, and use some kind of server-side paging, where the server sends just a single page at a time.

This scenario is supported by ngx-pagination by using the totalItems config option.

Given a server response json object like this:

{
  "count": 14453,
  "data": [
    { /* item 1 */ },
    { /* item 2 */ },
    { /* item 3 */ },
    { /*   ...  */ },
    { /* item 10 */ }
  ]
}

we should pass the value of count to the PaginatePipe as the totalItems argument:

<li *ngFor="let item of collection | paginate: { itemsPerPage: 10, currentPage: p, totalItems: res.count }">...</li>

This will allow the correct number of page links to be calculated. To see a complete example of this (including using the async pipe), see the demo.

Multiple Instances

It is possible to have any number of pagination pipe/controls pairs in the same template. To do this, just make use of the "id" attribute:

<ul>
  <li *ngFor="let item of collection | paginate: { itemsPerPage: 10, currentPage: p1, id: 'first' }"> ... </li>
</ul>
<pagination-controls (pageChange)="p1 = $event" id="first"></pagination-controls>

<ul>
  <li *ngFor="let item of collection | paginate: { itemsPerPage: 10, currentPage: p2, id: 'second' }"> ... </li>
</ul>
<pagination-controls (pageChange)="p2 = $event" id="second"></pagination-controls>

You can even have dynamically-generated instances, e.g. within an ngFor block:

export class MyComponent {
  p: number[] = [];
}
<div *ngFor="let id of [1, 2]; let i = index;">
  <ul>
    <li *ngFor="let item of collection | paginate: { itemsPerPage: 10, currentPage: p[i], id: id }">{{ item }}</li>
   </ul>
   <pagination-controls (pageChange)="p[i] = $event" [id]="id"></pagination-controls>
</div>

FAQ

Why does my filter not work with pagination?

A common issue is that people have trouble combining some kind of filter pipe with the paginate pipe. The typical symptom is that only the contents of the current page are filtered. The reason is that the paginate pipe must come after the filter pipe:

<ul>
  <li *ngFor="let item of collection | paginate: config | filter: queryString">WRONG</li> <-- This will not work as expected
</ul>

<ul>
  <li *ngFor="let item of collection | filter: queryString | paginate: config">CORRECT</li>
</ul>

How do I use the ngFor index with the pagination pipe?

If you need to use the index of the *ngFor in combination with pagination pipe, the index should be declared after the pagination pipe:

<ul>
  <li *ngFor="let item of collection; let i = index | paginate: config">WRONG</li>
</ul>

<ul>
  <li *ngFor="let item of collection | paginate: config; let i = index">CORRECT</li>
</ul>

How do I get the absolute index of a list item?

Using the index variable exposed by ngFor will always give you the index of the items relative to the current page. For example, if you have 10 items per page, you might expect the first item on page 2 to have an index value of 10, whereas you will find the index value to be 0. This is because ngFor has no knowledge of the pagination, it only ever knows about the 10 items of the current page.

However, the absolute index can be calculated according to the following formula:

absoluteIndex(indexOnPage: number): number {
  return this.itemsPerPage * (this.currentPage - 1) + indexOnPage;
}

In a template this would look something like:

<ul>
  <li *ngFor="let item of collection | paginate: { currentPage: currentPage, itemsPerPage: itemsPerPage }; let i = index">
    {{ itemsPerPage * (currentPage - 1) + i }}
  </li>
</ul>

Building from source

Requires globally-installed node (tested with v5.x) & npm.

npm install
npm run test
npm run build 

After running npm run build, the final output of the lib (which gets published to npm) is in the /dist/ngx-pagination folder.

To build the docs, run npm run build:docs, or serve them in dev mode with npm run start.

License

MIT

ngx-pagination's People

Contributors

alexkushnarov avatar anhtungbui avatar bernhardriegler avatar bnormoyle avatar dependabot[bot] avatar firstrow avatar fredsa avatar jfrankfurt avatar jpray avatar littlestudent avatar mathieulavigneopen avatar michaelbromley avatar mindfreakthemon avatar mohuk avatar psanetra avatar rafaelss95 avatar sebholstein avatar sibiraj-s avatar ssuperczynski avatar thebearso avatar truj avatar woofsbane 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  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

ngx-pagination's Issues

Unexpected token |

So after implementing i keep getting this error any ideas whats wrong

EXCEPTION: Error: Uncaught (in promise): Template parse errors:
Parser Error: Unexpected token | at column 29 in [ngFor let course of courses | paginate: { itemsPerPage: 2, currentPage: p }] in CourseListComponent@10:28 ("
</div>
<div class="row">
    <div class="list-group" [ERROR ->]*ngFor="let course of courses | paginate: { itemsPerPage: 2, currentPage: p }">
        <a href="#" c"): CourseListComponent@10:28

heres corelistcomponenets

import {Component} from 'angular2/core';
import {Api} from "../../../services/api";
import {CourseRemoveComponent} from "../remove/CourseRemoveComponent"
import {PaginatePipe, PaginationControlsCmp, PaginationService} from 'ng2-pagination';


import {
    ROUTER_DIRECTIVES
} from 'angular2/router';

@Component({
    selector: 'course',
    templateUrl: './app/components/courses/list/index.html',
    directives: [ROUTER_DIRECTIVES, CourseRemoveComponent, PaginationControlsCmp],
    pipes: [PaginatePipe],
    providers: [PaginationService]    
})

export class CourseListComponent {
    courses: Object;
    selectedCourse: Object = {};
    constructor(private _api: Api) {
        this.courses = this._api.courses$;
        this._api.getCourses();
    }
}

and the template

<div class="row">
    <h5 class="text-center text-muted">Course List</h5>
    <hr>
    <div class="pull-right" style="margin-bottom: 10px;">
        <button class="btn btn-md btn-success" [routerLink]="['CourseCreate']">
            Add new course
        </button>
    </div>
</div>
<div class="row">
    <div class="list-group" *ngFor="let course of courses | paginate: { itemsPerPage: 2, currentPage: p }">
        <a href="#" class="list-group-item clearfix">
            <span class="glyphicon glyphicon-file"></span>
            Author: {{ course.author }}, Name: {{ course.name }}, Price: {{ course.price }}
            <span class="pull-right">

                <button class="btn btn-md btn-success" [routerLink]="['CourseDetail', {id:course.id}]">
                    <span class="glyphicon glyphicon-search"></span>
                </button>

                <button class="btn btn-md btn-info" [routerLink]="['CourseEdit', {id:course.id}]">
                    <span class="glyphicon glyphicon-pencil"></span>
                </button>

                <button href="#remove-course" data-toggle="modal" class="btn btn-md btn-danger" (click)="selectedCourse = course">
                    <span class="glyphicon glyphicon-trash"></span>
                </button>
          </span>
        </a>
    </div>
    <course-remove [course]="selectedCourse"></course-remove>
</div>
<pagination-controls  id="some_id"
                      (pageChange)="pageChanged($event)"
                      maxSize="9"
                      directionLinks="true"
                      autoHide="true">
</pagination-controls>

Help wanted with ng-content

Angular 2 version: 2.0.0-rc.3

ng2-pagination version: 0.3.1

Description of issue: I'm trying to make a component who add pagination controls to my table, but my pagination controls seems to not doing anything.
What i'm doing wrong?

Steps to reproduce: See my Plnkr.

Expected result:
Get pagination page

Actual result:
Only the next button appear then disappear when we click on.

Demo: http://plnkr.co/edit/ToZeijKVoq7snVaf11TA?p=preview

Serial Number on rows

I am using ng2-pagination in my angular 2 application now I want to show serial number on rows increment to all the rows from 1 to nth row. I write some code but it only shows 1 to 10 number and it loads again from 1 to 10 number when I go to next page and so on.
my table show 10 records per page.
my code.
<tr *ngFor="let user of _data | paginate: config; let i=index"> <td>{{i+1}}</td> <td>{{user.FirstName}}</td> <td>{{user.LastName}}</td> <td>{{user.Email}}</td> </tr>
Image 1 Page
image

Image 2 Page
capture

Tests fail with rc3

Angular 2 version:
"@angular/common": "2.0.0-rc.3",
"@angular/compiler": "2.0.0-rc.3",
"@angular/core": "2.0.0-rc.3",
"@angular/forms": "0.1.1",
"@angular/http": "2.0.0-rc.3",
"@angular/platform-browser": "2.0.0-rc.3",
"@angular/platform-browser-dynamic": "2.0.0-rc.3",
"@angular/router": "3.0.0-alpha.7",
"@angular/router-deprecated": "2.0.0-rc.2",
"@angular/upgrade": "2.0.0-rc.3",
ng2-pagination version:
master
Description of issue:
passes 35/50 2 skipped
Steps to reproduce:
bump angular to rc3, npm install, typings isntall, npm run test

Any relevant code:

PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 35 of 50 (skipped 2) SUCCESS (0 secs / 1.308 secs)
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 35 of 50 (skipped 2) DISCONNECTED (11.333 secs / 1.308 secs)

Custom templates doesn't work

I copy pasted your custom templates example but it throws an error

TypeError: l_p4.isFirstPage is not a function in [p.isFirstPage() in MyAppComponent@47:57]

NPM Repository is out of date

NPMJS seems to have an old version of ng2-pagination, npmjs lists 0.3.2 as latest when 0.3.3 is the latest and contains a bug fix I require.

typings install issue

Angular 2 version: 2.0.0-rc.1

ng2-pagination version: 0.3.3

Description of issue: I've using the Angular2-seed project and when I try adding ng-2pagination to the project it errors with the following when doing the post install script:

c:\Temp\angular2-seed-master>npm install ng2-pagination --save

[email protected] postinstall c:\Temp\angular2-seed-master\node_modules\ng2
-pagination
npm run typings:install

[email protected] typings:install c:\Temp\angular2-seed-master\node_modules
\ng2-pagination
node node_modules/typings/dist/bin install

module.js:327
throw err;

Error: Cannot find module 'c:\Temp\angular2-seed-master\node_modules\ng2-paginat
ion\node_modules\typings\dist\bin'
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3

Steps to reproduce:

  1. Clone the latest version of Angular2-seed
  2. run 'npm-install' to install the current packages
  3. run 'npm install ng2-pagination --save'
  4. Error appears in output window

Pagination arrows remain when 0 items are showing after filter

Angular 2 version:

"angular2": "2.0.0-beta.11",
"es6-promise": "^3.0.2",
"es6-shim": "^0.35.0",
"ntypescript": "1.201605172209.1",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.2",
"systemjs": "0.19.24",
"vinyl-paths": "^2.1.0",
"zone.js": "0.6.4"

ng2-pagination version:

0.0.1

Description of issue:

When autoHide is true, the pagination controls completely hide when all the items fit in 1 page. This part works as expected.

However, when there are zero items after filtering, the pagination numbers hide but the arrows are still showing.

Steps to reproduce:

Set autoHide to true. Filter items so zero items are showing.

Expected result:

Zero items showing. Pagination controls completely hidden.

Actual result:

Zero items showing. Pagination numbers hidden. Pagination Next and Previous arrows still showing. This is inconsistent to when a few items all fit on one page.

Dart port

Hi,

I really like your library but because I'm using Dart with Angular2 instead of typescript I went ahead and made a port to Dart. Please see https://github.com/laagland/ng2-dart-pagination for the code. It is almost production ready, just a couple of bugs to squash.

Best,
Louis

Pagination with custom pipe

Hey,

Is anyone having issue with custom pipe?

Here is my custom pipe

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

// Tell Angular2 we're creating a Pipe with TypeScript decorators
@Pipe({
    name: 'showfilter',
    pure: false
})

export class ShowPipe {
    transform(value) {
        return value.filter(item => {
            return item.visible == true;
        });
    }
}

Component

import { ShowPipe } from '../pipes/show.pipe';
import { PaginatePipe, PaginationControlsCmp, PaginationService } from 'ng2-pagination';

@Component({
    selector: 'results',
    templateUrl: 'app/templates/results.html',
    pipes: [PaginatePipe, ShowPipe]
})

HTML

<flights *ngFor="let item of items | showfilter | paginate: { itemsPerPage: 10, currentPage: p }">
</flights>

When I have showfilter and paginate, no results are shown.

If I change HTML to

<flights *ngFor="let item of items | showfilter">
</flights>

Everything is working.

Now if I change HTML to

<flights *ngFor="let item of items | paginate: { itemsPerPage: 10, currentPage: p }">
</flights>

Pagination works.

Is there a way to have custom pipe working with paginate like the example on your website: http://michaelbromley.github.io/ng2-pagination/ (Full example)

[Feature] Templating the Collection

Hey guys was just wondering if its possible to template the elements which we are paginating so for example:

for (let i = 1; i <= 10; i++) {
            this.collection.push(`
               <h5>Step ${i}</h5>

            `);
        }

This prints out < h5 >Step 1..10< /h5 >

Instead of a larger text

Step 1

hope you get what I mean, is it possible to alter this behavior so that it does in fact use styling.

Excellent work

Down loaded your code and added to my project. Worked beautifully with no issues so far!

Custom pagination docs

Just a small note: local variable #p introduced in custom pagination example interferes with variable p used as currentPage value in pipe from first example. It leads to infinite loop and script termination by timeout.
This happened with angular 2.0RC1 and FF browser.

Possible typo in readme.md regarding property bindings

Angular 2 version: 2.0.0-beta.15

ng2-pagination version: 0.0.1

Description of issue: Possible typo in readme.md

Steps to reproduce: Currently, the PaginationControlsCmp section shows this example:

<pagination-controls  id="some_id"
                      (pageChange)="pageChanged($event)"
                      maxSize="9"
                      directionLinks="true"
                      autoHide="true">
</pagination-controls>

This demo doesn't seem to be changed when passing additional options. For example, directionLinks="true" doesn't remove the directional buttons. However, looking at the code here, we need to use property bindings:

<pagination-controls [id]="config.id"
                         [maxSize]="maxSize"
                         [directionLinks]="directionLinks"
                         [autoHide]="autoHide"
                         (pageChange)="onPageChange($event)"></pagination-controls>

Demo: (if possible, edit this Plunker demo and paste the link to your fork)

This doesn't seem to work, but this works.

Responsive design without directional buttons only shows a subset of numbers

Angular 2 version: 2.0.0-beta.15

ng2-pagination version: 0.0.1

Description of issue: Responsive design without directional buttons only shows a subset of buttons in PaginationControlsCmp.

Steps to reproduce:
Set directionLinks to false:

<pagination-controls (pageChange)="p = $event" #api [directionLinks]="false"></pagination-controls>

and look at the page in a small screen

Expected result: All the numbers in PaginationControlsCmp should be shown.

Actual result: Only a subset of buttons are shown:

screenshot from 2016-04-23 14-07-00

Demo: (if possible, edit this Plunker demo and paste the link to your fork)

Demo

onPageChange

Hi guys, just wondering if something like this is available in the current api, I know you can use it in the directive like (pageChange)="p = $event", but this feature could prove to be quite handy to be able to detect a onChange event with the page number etc.

Application becomes unstable after using pure: false in other pipes

Angular 2 version: 2.0.0-beta.15

ng2-pagination version: 0.0.1

Description of issue: Application becomes unstable after using the pattern

*ngFor="#item of objects | somePipe: value | paginate: { itemsPerPage: 10, currentPage: p }"

when somePipe has the attribute pure: false. value is supposed to change by the user.

Steps to reproduce: Set pure: false to any pipe processing the objects and pass the resulting objects to the pipe paginate.

Expected result: Application shouldn't become unstable.

Actual result: Most actions become really slow and closing the tab is necessary.

Demo: (if possible, edit this Plunker demo and paste the link to your fork)

Demo. Notice I set by default pure to true in the orderBy pipe. In a browser session you are not using, change it to false. After this, click on the "next" or "previous" buttons or click on the select menu to change the order of the items.

Property change within paginated item does not update view

Angular 2 version: 2.0.0-rc.1

ng2-pagination version: 0.3.0

Description of issue: Change within paginated item does not update view.

Steps to reproduce: With a list of objects to paginate, update property within one of the objects.

Expected result: View updates to show the new value.

Actual result: View does not update

Demo: http://plnkr.co/edit/LL6ubp7KCpytGmjV7cBO?p=preview

Click "update first" and it should change "item 1" to "first". With paginate, it does not update. If you remove paginate, it works.

Error Handling in Server Example

I have your server sample up and working as expected.

Can you give us a tip on how to handle errors with the async call. If the server throws and error I would like to present the user with a message. Usually I would handle this in the subscribe, but there is now subscribe in this case?

__Allan

Control does not load at all

Angular 2 version: RC1

ng2-pagination version: 0.3.4

Description of issue:
My component just does not load when I use the pipe in my component. No errors. Just nothing.
I've put break points in the code, and I can see the pipe and service are being returned, but they are never instantiated (e.g. checkConfig of the pipe is not being called).

I'm using System.js

I really don't know how to investigate this further?

Features: go first page, go last page

Hi,
I'm using custom template and i need to show two links, "go to first page" and "go to last page".
The component already has this feature? How can i do that?

thks,
NS

Add systemjs bundle

Some people might not want to use the commonjs files and may prefer a systemjs (System.register) bundle. This is also useful for testing things out in Plunker, JsBin etc. See the Angular 2 docs on bundling as a starting point.

If items empty

Hi, thanks for contributing!

As a template, you can specify that there are no elements for pagination?
Example:

<tr *ngIf="config_pagination.totalItems == 0"><td>Products was empty</td></tr>
<tr *ngFor="#product of productsAsync | async | paginate: config_pagination; #idx = index">
...
</tr>

If there is no product - that provides the latest products paginator. Although I must issue a blank list. How can I fix it?
Thanks

I return Observable.of([]) if product was empty. This resolve my problem.

Pagination controls can not be before the paginated content

If I place <paginagtion-controls ... /> before the element with paginate pipe the app crashes with

TypeError: Cannot read property 'currentPage' of undefined
    at PaginationControlsCmp.updatePages (pagination-controls-cmp.js:60)
    at PaginationControlsCmp.ngOnChanges (pagination-controls-cmp.js:82)

because this.service.getInstance(this.id) returns with undefined instead of the pagination service instance.

Unexpected token < when setting up pagination

Hi, thanks for contributing!

This project is maintained in my spare time, so in order to help me address your issue as quickly as
possible, please provide as much of the following information as you can.

-- Michael

Angular 2 version:
RC1

ng2-pagination version:
Not sure, I just downloaded it via npm

Description of issue:
(index):40 Error: SyntaxError: Unexpected token <
at Object.eval (http://localhost:3000/src/tmp/app/components/Blog/list/BlogListComponent.js:15:24)
at eval (http://localhost:3000/src/tmp/app/components/Blog/list/BlogListComponent.js:44:4)
at eval (http://localhost:3000/src/tmp/app/components/Blog/list/BlogListComponent.js:45:3)
Evaluating http://localhost:3000/ng2-pagination
Evaluating http://localhost:3000/src/tmp/app/components/Blog/list/BlogListComponent.js
Evaluating http://localhost:3000/src/tmp/app/components/init/InitComponent.js
Evaluating http://localhost:3000/src/tmp/app/main.js
Error loading http://localhost:3000/src/tmp/app/main.js(anonymous function) @ (index):40g @ es6-shim.js:2194(anonymous function) @ es6-shim.js:2182ZoneDelegate.invoke @ zone.js:323Zone.run @ zone.js:216(anonymous function) @ zone.js:571ZoneDelegate.invokeTask @ zone.js:356Zone.runTask @ zone.js:256drainMicroTaskQueue @ zone.js:474ZoneTask.invoke @ zone.js:426

Steps to reproduce:
No steps really I use the code in the examples but when I add in the directive for PaginationControlsCmp i get the above error

Custom templates cause ExpressionChangedAfterItHasBeenCheckedException

When I try to create a custom template within the controls, it throws the exception:

Expression p.isFirstPage() has changed after it was checked. Previous value: 'false'. Current value: 'true' in [p.isFirstPage()]

Which I understand is something fixable by using a change detector ref, but efforts so for haven't proved useful.
I could try and reproduce with plunkr but I thought I'd check if you had tested this with recent versions of angular2?

about updating to angular version 2.0.0-rc.1

Hi, thanks for contributing!

This project is maintained in my spare time, so in order to help me address your issue as quickly as
possible, please provide as much of the following information as you can.

-- Michael

Hi.

I use ng2 pagination for developing angular 2.

well. angular team updated angular version to 2.0.0-rc.1.

I hope to update ng-pagination with angualr 2.0.0-rc.1.

thank you. Have a nice day~~~

Angular 2 version: 2.0.0-rc.1

ng2-pagination version: 0.0.1-beta.2

Description of issue: supporting angular version 2.0.0-rc.1

Steps to reproduce:

Expected result: version up ng2-pagination suppoting angular version 2.0.0-rc.1

Actual result: Thank you very much? :)

Demo: (if possible, edit this Plunker demo and paste the link to your fork)

Any relevant code:


Custom template bug

You have a bug with a custom template in live demo, check this:

image

Why is a custom template when the template is default and is not overwritten?

Thanks

Angular Universal server side render pagination-controls

Angular 2 version:

"angular2": "2.0.0-beta.12",

ng2-pagination version:

"ng2-pagination": "0.0.1",

Description of issue:

When using ng2-pagination with Angular Universal the pagination-control is not being rendered on the server side.

Steps to reproduce:

clone https://github.com/angular/universal-starter and add ng2-pagination

Expected result:

noJS navigation with the pagination-controls component

Actual result:

pagination-controls component templates are not rendered

Demo: (if possible, edit this Plunker demo and paste the link to your fork)

Any relevant code:


Pagination controls are misaligned after adding Bootstrap

Angular 2 version:
Angular 2.0.0-beta.12
ng2-pagination version:
0.0.1-beta.3
Description of issue:
I believe the latest version of Bootstrap (3.3.6) messes up the alignment of the pagination controls.
Steps to reproduce:
Demo. Notice I added bootstrap. After this, the previous and next buttons are misaligned.
Expected result:
Buttons should remain aligned.

In a naive attempt to fix this, I added Foundation but that didn't help.

Exception after updated to Angular "2.0.0-rc.2"

I updated to Angular "2.0.0-rc.2", from an earlier beta version "2.0.0-beta.13", I am getting errors in pagination

EXCEPTION: Error in app/users/user-list.component.html:37:13 angular2.dev.js:25644
EXCEPTION: Error in app/users/user-list.component.html:37:13BrowserDomAdapter.logError @ angular2.dev.js:25644 angular2.dev.js:25644 
ORIGINAL EXCEPTION: TypeError: Cannot read property 'totalItems' of undefinedBrowserDomAdapter.logError @ angular2.dev.js:25644 angular2.dev.js:25644 
ORIGINAL STACKTRACE:BrowserDomAdapter.logError @ angular2.dev.js:25644 angular2.dev.js:25644 TypeError: Cannot read property 'totalItems' of undefined     at PaginatePipe.transform (paginate.pipe.ts:42)     at AppView._View_UserListComponent0.detectChangesInternal (UserListComponent.template.js:527)     at AppView.detectChanges (angular2.dev.js:23638) 

I noticed some compiler error too:

Does this library support dynamic Paging?

i tried this library and it works good for local list, and would like to use it for some api that returns json (a list + total items count). But once I bind the "totalItems" property and when the list is updated by the returned json, the browser get frozen.

will this library work in this case?

Error in installing pagination

Hi, thanks for contributing!

This project is maintained in my spare time, so in order to help me address your issue as quickly as
possible, please provide as much of the following information as you can.

-- Michael

Angular 2 version:"@angular/common": "2.0.0-rc.4",

ng2-pagination version: latest

Description of issue: Gives some warning errors when I issue the command
npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: [email protected]
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

Steps to reproduce:
npm install ng2-pagination
Expected result:
clean install
Actual result:
I checked it is there in node_modules\ng2-pagination
in my component I put in my component
import {PaginatePipe, PaginationControlsCmp, PaginationService} from 'ng2-pagination';
localhost/:25 Error: Error: XHR error (404 Not Found) loading http://localhost:3001/ng2-pagination(โ€ฆ)

I also tried putting the js file in my index.html:

<script src="https://rawgit.com/michaelbromley/ng2-pagination/master/dist/ng2-pagination-bundle.js"></script>

then it works!

Any relevant code:


Pagination component appears twice when using custom template

Angular 2 version: 2.0.0-rc.1

ng2-pagination version: 0.3.2

Description of issue: When using a custom template on pagination, the pagination tool appears twice, one is the templated pagination and the other is the original pagination

Steps to reproduce: Add pagination with custom template

Expected result: A single templated pagination component

Actual result: 2 pagination components, 1 templated and the other default template

Demo: (if possible, edit this Plunker demo and paste the link to your fork)

Any relevant code:


chrome_2016-06-09_15-28-00

Update Content on Collection array change

Hey guys,
is it possible to update the content of the current page after the content of the array is changed, for some reason it changes the contents after I change page and come back so there seems to be a detection change within the onPageChange listener just wondering if there is any way we can call this to update it on content change.

Updating the browser address bar when paginating

Angular 2 version:
RC.1
ng2-pagination version:
0.3.0
Description of issue:
Updating of the browser address bar doesn't get updated while paginating, this in turn doesn't allow users to easily share links of specific pages
Steps to reproduce:
Just paginate between pages of results
Expected result:
the address bar should get updated, for ex. www.example.com/articles should be updated to www.example.com/page/2 when a user paginate to the second page (the url addition of "page/#" should be customizable as its also an SEO issue).

It will be even better if this feature will be optional so the dev could decide if he want it or not.
Actual result:
The address bar (and also the browser history) doesn't change when paginating
Demo:
I guess no demo is needed, feel free to let me know otherwise

Thanks a lot for this project!

Hide "You're on page 1"

"You're on page 1"

Is there currently a way to hide this text or to change it/position it/its value elsewhere?

Looks like this atm and Id like to have it inline:
"Previous page"
You're on page 1
"Page 2" "Next page"

Also having an issue with pagecontrols::

can't be set before the Pagepipe I am always getting a page not set error
Helping myself out with ngIf

Show all items

Hi,

Thanks for your work. I found an issue:

When you want to show all items, you have to put 0 as itemsPerPage. The problem is in pagination control. You can see "infinte button" in navigation control.

You can reproduce this in your plnk by set itemsPerPage at 0.
Overwhise you can do it too in your "Full example".

Thanks

how reload paging when comment

i used ionic 2 and angular2 for build app
i used ng2-pagination for paging comment

when i post new comment. i used this.comments.unshift(comment); for insert first comment
how in template will show this comment in first and page 1.

i must be next page 2 then pervious page 1 , it show that

i want new comment show in first and in page1 , don't next page2 then pervious page1

Does the pagination pipe need to be stateless?

I've created a order by pipe that only refreshes the collection once you paginate.
Im guessing this has to do with the default stateless nature of pipes in ng2?.
Possible solutions:

  1. Subscribe to Emitted event that refreshes the collection
  2. Add {pure: false} to the @pipe decoration config

Is there any other way I can refresh the collection programatically?

How do I override the css?

I've tried to override the font size/font/colors/etc and have had no luck. Also, it doesn't look like you can currently replace the 'Previous' or 'Next' text, is that correct.

I've tried a couple of the examples below to no avail. Am I doing something wrong?

[override] .bulkResults pagination-controls .ng2-pagination li {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  font-size: 0.875rem;
  margin-right: 0.0625rem;
  border-radius: 0;
  color: #ffffff;
}

.bulkResults pagination-controls a:hover,
.bulkResults pagination-controls button:hover {
  background: #ffa500;
}

number: number returns NaN

Hello,
For some reason $event returns NaN. Please see my code below.

Angular 2 version: 2.0.0-beta.17

ng2-pagination version: 0.2.0

Description of issue: When triggering function (pageChange)="onPageChanged($event)", $event returns NaN instead of the page number.

Steps to reproduce: Click on Next in the pagination. (no numbers showing, just next)

Expected result: Receive a page number

Actual result: Receiving NaN

Demo: (if possible, edit this Plunker demo and paste the link to your fork)

Any relevant code:

import 'reflect-metadata';
import {Component} from 'angular2/core';
import {Parties} from '../../../collections/parties';
import {PartiesForm} from '../parties-form/parties-form';
import {RouterLink} from 'angular2/router';
import {MeteorComponent} from 'angular2-meteor';
import {LoginButtons, InjectUser} from 'angular2-meteor-accounts-ui';
import {ReactiveVar} from 'meteor/reactive-var';
import {PaginationService, PaginatePipe, PaginationControlsCmp} from 'ng2-pagination';
//import {Counts} from 'meteor/tmeasday:publish-counts';

@Component({
    selector: 'parties-list',
    templateUrl: '/client/views/parties-list/parties-list.html',
    directives: [PartiesForm, RouterLink, LoginButtons, PaginationControlsCmp],
    pipes: [PaginatePipe],
    providers: [PaginationService]
})

@InjectUser()

export class PartiesList extends MeteorComponent {
    parties: Mongo.Cursor<Party>;
    pageSize: number = 10;
    curPage: ReactiveVar<number> = new ReactiveVar<number>(1);
    nameOrder: ReactiveVar<number> = new ReactiveVar<number>(1);
    partiesSize: number = 0;
    location: ReactiveVar<string> = new ReactiveVar<string>(null);
    user: Meteor.User;

    constructor() {
        super();
        this.autorun(() => {
            let options = {
                limit: this.pageSize,
                skip: (this.curPage.get() - 1) * this.pageSize,
                sort: {name: this.nameOrder.get()}
            };
            this.subscribe('parties', options, this.location.get(), () => {
                this.parties = Parties.find({}, {sort: {name: this.nameOrder.get() }});
            }, true);
        });
//        this.autorun(() => {
//            this.partiesSize = Counts.get('numberOfParties');
//        }, true);
    }

    removeParty(party) {
        Parties.remove(party._id);
    }

    search(value: string) {
        this.curPage.set(1);
        this.location.set(value);
    }

    onPageChanged(page: number) {
//        console.log(page);
        this.curPage.set(page);
    }
}

isFirstPage() triggers "Expression 'm.isFirstPage() has changed after it was checked"

Angular 2 version: 2.0.0-beta.15

ng2-pagination version: 0.0.1

Description of issue: Using the default template for PaginationControlsCmp, there is an error Expression 'm.isFirstPage() in App@2:10' has changed after it was checked. Previous value: 'false'. Current value: 'true' after m.isFirstPage() is checked.

Steps to reproduce: Maybe there is an alternative to this, but having something like <pagination-controls #m (pageChange)="p = $event" #api></pagination-controls> in order to access the API in the template, causes the previous error after m.isFirstPage() is evaluated.

Expected result: No error is thrown or possibly an alternative to #m in the pagination-controls element.

Demo: (if possible, edit this Plunker demo and paste the link to your fork)

Demo

Thanks

Pipe not support Mongo cursor as Collections

Now, I am following this tutorial: http://www.angular-meteor.com/tutorials/socially/angular2/search-sort-pagination-and-reactive-vars for sorting and paginate variable users: Mongo.Cursor<any> = null;
Although I have set totalItems = 100, but your plugin display nothing
selection_092

I try to debug, and found that problem in file: node_modules/ng2-pagination/dist/paginate-pipe.js

PaginatePipe.prototype.transform = function (collection, args) {
    // When an observable is passed through the AsyncPipe, it will output
    // `null` until the subscription resolves. In this case, we want to
    // use the cached data from the `state` object to prevent the NgFor
    // from flashing empty until the real values arrive.
    if (args instanceof Array) {
        // compatible with angular2 before beta16
        args = args[0];
    }
    if (!(collection instanceof Array)) {
        var _id = args.id || this.service.defaultId;
        if (this.state[_id]) {
            return this.state[_id].slice;
        }
        else {
            return collection;
        }
    }
    var serverSideMode = args.totalItems !== undefined;
    var instance = this.createInstance(collection, args);
    var id = instance.id;
    var start, end;
    var perPage = instance.itemsPerPage;
    this.service.register(instance);
    if (!serverSideMode && collection instanceof Array) {
        perPage = perPage || LARGE_NUMBER;
        start = (instance.currentPage - 1) * perPage;
        end = start + perPage;
        var isIdentical = this.stateIsIdentical(id, collection, start, end);
        if (isIdentical) {
            return this.state[id].slice;
        }
        else {
            var slice = collection.slice(start, end);
            this.saveState(id, collection, slice, start, end);
            this.service.change.emit(id);
            return slice;
        }
    }
    // save the state for server-side collection to avoid null
    // flash as new data loads.
    this.saveState(id, collection, collection, start, end);
    return collection;
};

The main proplem in this code: It make function return and not run this.service.register(instance);

    if (!(collection instanceof Array)) {
        var _id = args.id || this.service.defaultId;
        if (this.state[_id]) {
            return this.state[_id].slice;
        }
        else {
            return collection;
        }
    }

Pagination pipe simply won't know how to calculate its size when collection not is Array

Can you support more type of collections ? Or tell me the way to set totalItems of PaginationService in this case !

Unexpected token <

I'm a angular newb so probably doing something wrong but after adding this to a previously working component I get the error Unexpected token <

import {Component, OnInit} from 'angular2/core';
import {PaginatePipe, PaginationControlsCmp, PaginationService} from 'ng2-pagination';
import {User} from '../../../models/user';
import {UserService} from '../../../services/user.service';

@Component({
  selector: 'user-list',
  templateUrl: './app/components/user/list/user-list.html',
  directives: [PaginationControlsCmp],
  pipes: [PaginatePipe],
  providers: [PaginationService]
})
export class UserListComponent {
  users: User[];
  constructor(private _service: UserService) { }
  ngOnInit() {
    this._service.getUsers().then(users => this.users = users);
  }
}

SystemJS not defined

Im using RC1. As part of my production build step I compile and concat all the code. everything compiles no problem but using the <script src="../node_modules/ng2-pagination/dist/ng2-pagination-bundle.js"> </script> script I always end up getting SystemJS not defined errors.

Also as part of the build step I remove the systemjs block from the document using gulp useref so it obviously has to do with that. Just wondering if you have any examples for this kind of build setup and issue ?

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.