【问题标题】:How can I create a pagination component in Angular 4? [closed]如何在 Angular 4 中创建分页组件? [关闭]
【发布时间】:2018-01-23 18:08:55
【问题描述】:

我有一个 API 端点,例如 /list/students?page=5&rows=10,其分页参数为 pagesize。我想创建一个 angular2 分页组件。

输入参数将是

  • 页面
  • 尺寸

另外,我想用箭头按钮转到特定的页面和大小。

如何实现这个组件?

【问题讨论】:

    标签: angular components angular2-forms


    【解决方案1】:

    你可以使用我下面的代码和服务来创建一个分页组件

    app.component.html

    <paging-component
      [TotalItems]="pagination.TotalItems"
      [CurrentPage]="pagination.CurrentPage"
      [PageSize]="pagination.PageSize"
      [TotalPageLinkButtons]="pagination.TotalPageLinkButtons"
      [RowsPerPageOptions]="pagination.RowsPerPageOptions"
      (onPageChange)="myChanges($event)"></paging-component>
    

    app.component.ts 在下面;

    import {Component} from '@angular/core';
    
    @Component({
      selector   : 'app-root',
      templateUrl: './app.component.html',
      styleUrls  : ['./app.component.css']
    })
    export class AppComponent {
    
      pagination = {
        TotalItems: 100,
        CurrentPage: 1,
        PageSize: 10,
        TotalPageLinkButtons: 5,
        RowsPerPageOptions: [10, 20, 30, 50, 100]
      };
    
      /* Paging Component metod */
      myChanges(event) {
        this.pagination.CurrentPage = event.currentPage;
        this.pagination.TotalItems = event.totalItems;
        this.pagination.PageSize = event.pageSize;
        this.pagination.TotalPageLinkButtons = event.totalPageLinkButtons;
      }
    }
    

    app.component.module

    import {BrowserModule} from '@angular/platform-browser';
    import {NgModule} from '@angular/core';
    import {FormsModule} from '@angular/forms';
    import {HttpModule} from '@angular/http';
    
    import {AppComponent} from './app.component';
    import {PagingComponent} from './components/paging-component/paging-component.component';
    import {PagingService} from './service/paging-service.service';
    
    @NgModule({
      declarations: [
        AppComponent,
        PagingComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule
      ],
      providers: [ PagingService],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    paging-service.service.ts 是

    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class PagingService {
    
    
      /**
       * @param totalItems : Total items to be listed
       * @param currentPage : Current page number ( Pages starting from 1 not 0)
       * @param pageSize : The number of items in the page
       * @param totalPageLinkButtons : The number of total page link buttons
       * @returns {{
       * startPage: number,
       * endPage: number,
       * startIndex: number,
       * endIndex: number,
       * totalPageLinkButtons: number,
       * totalItems: number,
       * currentPage: number,
       * pageSize: number,
       * totalPages: number,
       * pages: (Observable<number>|any)
       * }}
       */
      getPagingServiceItems(totalItems: number, currentPage: number = 1, pageSize: number = 10, totalPageLinkButtons: number = 5) {
    
        totalItems = totalItems || 1;
    
        /* if currentPage not exists default value will be '1' */
        currentPage = currentPage || 1;
    
        /* The default value of the number of items in the page is 10 if not exist */
        pageSize = pageSize || 10;
    
        /* The default value of the number of total page link buttons is 10 if not exist */
        totalPageLinkButtons = totalPageLinkButtons || 10;
    
        /* calculate total pages  */
        const totalPages = Math.ceil(totalItems / pageSize);
    
    
        let startPage: number; // start Page Button number
        let endPage: number;   // end Page Button number
    
        if (totalPages <= totalPageLinkButtons) {
    
          // less than totalPageButtons then show all
          // 1,2,3,.., totalPages are buttons
          startPage = 1;
          endPage = totalPages;
        } else {
          // more than totalPageButtons then calculate start and end pages
          // currentPage will be on the center of the paging
    
          if (currentPage <= Math.ceil(totalPageLinkButtons / 2)) {
            startPage = 1;
            endPage = totalPageLinkButtons;
          } else if (currentPage + Math.ceil(totalPageLinkButtons / 2) > totalPages) {
            startPage = totalPages - totalPageLinkButtons + 1;
            endPage = totalPages;
          } else {
            startPage = currentPage - Math.ceil(totalPageLinkButtons / 2) + 1;
            endPage = startPage + totalPageLinkButtons - 1;
          }
        }
    
        // calculate start and end item indexes
        // Indexes are started from 0 ! It is important
    
        const startIndex = (currentPage - 1) * pageSize;
        const endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
    
        const pages = [];
        // create an array of pages to ng-repeat in the pager control
        for ( let i = startPage; i <= endPage ; i++) {
          pages.push(i);
        }
    
        // return object with all paging properties required by the view
        return {
          startPage           : startPage,
          endPage             : endPage,
          startIndex          : startIndex,
          endIndex            : endIndex,
          totalPageLinkButtons: totalPageLinkButtons,
          totalItems          : totalItems,
          currentPage         : currentPage,
          pageSize            : pageSize,
          totalPages          : totalPages,
          pages               : pages
        };
      }
    
    
    }
    

    【讨论】:

    • 嗨@Dr。极客,能不能加分页组件代码
    • 它只是复制和粘贴代码,既不详细也不解释...请描述它并添加分页组件,否则此代码无用。
    【解决方案2】:

    您可以简单地创建自己的分页组件。

    如果您在项目中使用 Angular CLI,您可以使用 ng g c pagination 在您的应用文件夹中创建新组件。如果您不使用 Angualr CLI,则创建文件夹分页和以下文件:

    • pagination.ts // 用于模型/界面
    • pagination.component.ts // 用于逻辑
    • pagination.component.html // 模板
    • pagination.component.css // 样式

    pagination.ts

    export class Page {
        page: number;
        itemsPerPage: number;
    }
    

    pagination.component.ts

    import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
    import { Page } from './pagination';
    
    @Component({
      selector: 'app-pagination',
      templateUrl: './pagination.component.html',
      styleUrls: ['./pagination.component.css']
    })
    export class PaginationComponent implements OnInit {
    
      @Input() maxPages: number;
      @Input() current: number;
      @Input() postsPerPage: number[];
      @Input() itemsPerPage: number;
    
      @Output() changePage = new EventEmitter();
    
      pages: any[] = [];
      pageModel: Page = {
        page: this.current,
        itemsPerPage: this.itemsPerPage
      };
    
      constructor() { }
    
      ngOnInit() {
        if (this.maxPages) {
          this.createPages();
        }
      }
    
      setPage(page: number, perPage: number) {
        this.pageModel.page = page;
        this.pageModel.itemsPerPage = perPage;
        this.changePage.emit(this.pageModel);
      }
    
      createPages() {
        for(let i=1; i <= this.maxPages; i++) {
          this.pages.push(i);
        }
      }
    
    }
    

    pagination.component.html

    在我自己的项目中,我使用引导程序,但您可以根据需要简单地自定义此模板。

    <div class="row">
      <div class="col-lg-6">
        <nav aria-label="Pagination" *ngIf="maxPages > 1">
          <ul class="pagination">
            <li [class.disabled]="current == 1">
              <a href="javascript:;"
                 (click)="setPage(current-1, itemsPerPage)"
                 aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
              </a>
            </li>
            <li *ngFor="let page of pages;" [class.active]="page == current">
              <a href="javascript:;" (click)="setPage(page, itemsPerPage)">{{ page }}</a>
            </li>
            <li [class.disabled]="current == maxPages">
              <a href="javascript:;" (click)="setPage(current+1 ,itemsPerPage)" aria-label="Next">
                <span aria-hidden="true">&raquo;</span>
              </a>
            </li>
          </ul>
        </nav>
      </div>
      <div class="col-lg-6 text-right per-page">
        <nav aria-label="Anzahl der Beiträge pro Seite">
          <p>Anzahl der Beiträge pro Seite:</p>
          <ul class="pagination">
            <li *ngFor="let perPage of postsPerPage;" [class.active]="perPage == itemsPerPage">
              <a href="javascript:;" (click)="setPage(current, perPage)">{{ perPage }}</a>
            </li>
          </ul>
        </nav>
      </div>
    </div>
    

    pagination.component.css

    这里有一些样式。

    .per-page nav p {
        display: inline-block;
        margin: 25px 10px;
        font-weight: bold;
        padding: 2px 0;
    }
    
    .per-page nav .pagination {
        float: right;
    }
    

    创建此文件后,您应该将此组件导入您的app.module.ts

    以下是使用 API (如端点)使用此分页的示例:

    students-list.component.html

    将分页组件放入您的模板并从中获取发出的事件。您还应该通过输入向分页组件发送一些数据。

    <app-pagination [maxPages]="maxPages"
                    [current]="currentPage"
                    [postsPerPage]="postsPerPage"
                    [itemsPerPage]="itemsPerPage"
                    (changePage)="pageChanged($event)"></app-pagination>
    

    在您的students-list.component.ts 中,您应该定义一些默认值,您可以使用已发出的事件。

    students-list.component.ts

    itemsPerPage: number = 25;
    postsPerPage: number[] = [25, 50, 100];
    
    constructor(private studentService: StudentService) {}
    
    pageChanged(event) {
        this.page = event.page;
        this.itemsPerPage = event.itemsPerPage
        this.loadStudentsByPage(this.page, this.itemsPerPage);
    }
    
    loadStudentsByPage(page: number, rows: number) {
        let params = new URLSearchParams(); 
        params.set('page', page.toString());
        params.set('rows', rows.toString());
        this.isLoading = true;
        this.studentService.getStudentListByParams(params).subscribe(data => {
          this.students= data;
          this.isLoading = false;
        }, error => {
          this.isLoading = false;
          console.log(error);
        });
    }
    

    students-list.service.ts

    下面是从 API 获取学生的服务函数示例:

    headers = new Headers({'Content-Type': 'application/json', 'Accept': 'application/json'});
    
    getStudentListByParams(params: URLSearchParams): Observable<StudentsModel> {
        const endpoint = domain + '/list/students';
        return this.http
          .get(endpoint, { search: params, headers: this.headers })
          .map((res: Response) => res.json())
          .catch((e) => this.handleError(e));
    }
    

    希望你能用这个例子,而且通俗易懂。

    【讨论】:

    • 你能提供plunker链接吗
    • max pages ????....你能描述一下它是如何生成的吗?
    猜你喜欢
    • 2018-05-08
    • 2015-02-18
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 2017-12-01
    相关资源
    最近更新 更多