65.9K
CodeProject 正在变化。 阅读更多。
Home

Angular2中的表格分页与搜索栏

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.98/5 (19投票s)

2016 年 11 月 7 日

CPOL

4分钟阅读

viewsIcon

78352

downloadIcon

34

您将逐步学习如何使用Angular2创建表格分页和搜索栏。

引言

通过本文,您将学习使用 Angular2

  • 如何创建一个带分页的表格
  • 如何实现一个搜索框来过滤表格内容。

背景

为了更好地理解本文,最好您对以下内容有深入的了解:

  • 数据绑定
  • TypeScript
  • Angular2

Using the Code

A) 先决条件

在开始编码之前,我建议您从 Angular 2 网站下载 Angular2 模板:Angular2 快速入门

当您在命令行运行 tree 命令时,应该会看到以下文件夹结构

B) 构建应用程序

要构成此示例,您首先应该创建构建分页和搜索逻辑的 TypeScript 类。

**) Angular2 TypeScript 类

本节将描述我为使用 TypeScript 构建应用程序核心所遵循的步骤

创建 Product.ts

这个类包含了一系列描述产品对象的属性。它将用于定义 'productList' 数组中的一个条目。

export class Product {
   constructor(
    public id : number,    
    public name : string,    
    public description : string
   ){

   }
}

创建 Data.ts

这个文件包含一个名为 'productList' 的 JSON 数组的声明和初始化,稍后将用于填充 HTML 视图中的产品列表表格。

productList’ 是一个 Product 数组,因此我们导入了 'Person' 类。

import {Product} from './Product';
export var productList: Product[] = [
  {"id": 1, "name": "juice 1", "description": "description 1"},
  {"id": 2, "name": "juice 2", "description": "description 2"},
  {"id": 3, "name": "juice 3", "description": "description 3"},
  {"id": 4, "name": "juice 4", "description": "description 4"},
  {"id": 5, "name": "juice 5", "description": "description 5"},
  {"id": 6, "name": "juice 6", "description": "description 6"},
  {"id": 7, "name": "juice 7", "description": "description 7"},
  {"id": 8, "name": "juice 8", "description": "description 8"},
  {"id": 9, "name": "juice 9", "description": "description 9"},
  {"id": 10, "name": "orange 1", "description": "description 1"},
  {"id": 11, "name": "orange 2", "description": "description 2"},
  {"id": 12, "name": "orange 3", "description": "description 3"},
  {"id": 13, "name": "orange 4", "description": "description 4"},
  {"id": 14, "name": "orange 5", "description": "description 5"},
  {"id": 15, "name": "orange 6", "description": "description 6"},
  {"id": 16, "name": "orange 7", "description": "description 7"},
  {"id": 17, "name": "orange 8", "description": "description 8"},
  {"id": 18, "name": "orange 9", "description": "description 9"},
  {"id": 19, "name": "orange 10", "description": "description 10"},
  {"id": 20, "name": "orange 11", "description": "description 11"},
  {"id": 21, "name": "orange 12", "description": "description 12"},
  {"id": 22, "name": "orange 13", "description": "description 13"},
  {"id": 23, "name": "orange 14", "description": "description 14"},
  {"id": 24, "name": "orange 15", "description": "description 15"},
  {"id": 25, "name": "orange 16", "description": "description 16"},
  {"id": 26, "name": "orange 17", "description": "description 17"},
]

创建 app.paginationComponent.ts

这是主类,它拥有带有必需绑定的 HTML 模板,以及分页和搜索逻辑的实现。

首先,您需要导入所需的 *.ts 类来构建 Pagination 类。

Pagination 类将包含构成 Product 表格条目、分页和搜索输入的属性和函数。此外,它将处理由于绑定而从用户界面接收到的事件。

为了实现分页和过滤系统,我使用了这些

  • filteredItems 属性:一个 'Product' 数组,用于存储 'FilterByName' 函数执行的搜索过程的结果。
  • pageSize 属性:表示每页的条目数。
  • pages :分页栏中最多可显示的页码数量(即 'pagesIndex' 数组的大小)。
  • pageNumber 属性:根据 'pageSize' 值,可以从 'ProductList' 中推断出的最大页数。
  • currentIndex 属性:当前选中页的索引。
  • items 属性:当前选中页的内容。
  • pagesIndex 属性:包含分页栏中显示的数字系列。
  • pageStart 属性:这是分页栏中的起始页索引。
  • inputName 属性:用于搜索新的产品列表,其中每个产品的 'name' 属性值包含 'inputName' 中的文本。
  • Constructor 方法:初始化 'filterditems'(从 'ProductList')和分页。
  • Init 方法 :用于计算分页值,并更新视图屏幕。
  • FilterByName 方法:此函数返回一个产品列表,其中 'inputName' 中的文本是产品名称的子字符串。结果将存入 'filteredItems' 列表。
  • refreshItems 方法:根据以下属性的值主要刷新表格内容:‘currentIndex’、‘pageSize’、'pages' 和 'pageStart'。
  • prevPage 方法:此函数会将选定页索引(‘currentIndex’)减一,并刷新显示。
  • nextPage 方法:此函数会将选定页索引(‘currentIndex’)加一,并刷新显示。
  • setPage 方法:当用户从分页中选择一个数字时调用。它将修改 'currentIndex' 值并刷新视图。
import { Component, NgModule } from '@angular/core';
import {Product} from './Product';
import {productList} from './data';
@Component({
 selector: 'my-pagination',
 template: ` 
   <div class="form-group">
         <label>Filter </label>
         <input  type="text"  id="inputName" [(ngModel)]="inputName"/>
         <input type="button" (click)="FilterByName()" value="Apply"/>
   </div>
   <div class='row'>
    <div class="panel panel-default">
    <!-- Default panel contents -->
    <div class='panel-heading'>Product List</div>
    <div class='panel-body'>
         <table class="table table-bordered table-condensed ">
            <thead>
               <th>Id</th>
               <th>Name</th>
               <th>Description</th>
            </thead>
            <tbody>
               <tr *ngFor="let item of items">
                  <td>{{item.id}}</td>
                  <td>{{item.name}}</td>
                  <td>{{item.description}}</td>
               </tr>
            </tbody>
         </table>
         <div class="btn-toolbar" role="toolbar" style="margin: 0;">
          <div class="btn-group">
               <label style="margin-top:10px">Page {{currentIndex}}/{{pageNumber}}</label>
            </div>
            <div class="btn-group pull-right">
               <ul class="pagination" >
                  <li [ngClass]="{'disabled': (currentIndex == 1 || pageNumber == 0)}" ><a  (click)="prevPage()" href="#">Prev</a></li>
                     <li *ngFor="let page of pagesIndex"  [ngClass]="{'active': (currentIndex == page)}">
                        <a (click)="setPage(page)" href="#" >{{page}}</a>
                     </li>
                  <li [ngClass]="{'disabled': (currentIndex == pageNumber || pageNumber == 0)}" ><a   (click)="nextPage()" href="#">Next</a></li>
               </ul>
            </div>
         </div>
      </div>
   </div>   
  `,
 styles: ['.pagination { margin: 0px !important; }']
})
export class Pagination {

   filteredItems : Product[];
   pages : number = 4;
  pageSize : number = 5;
   pageNumber : number = 0;
   currentIndex : number = 1;
   items: Product[];
   pagesIndex : Array<number>;
   pageStart : number = 1;
   inputName : string = '';

   constructor( ){
         this.filteredItems = productList;
       this.init();
   };
   init(){
         this.currentIndex = 1;
         this.pageStart = 1;
         this.pages = 4;

         this.pageNumber = parseInt(""+ (this.filteredItems.length / this.pageSize));
         if(this.filteredItems.length % this.pageSize != 0){
            this.pageNumber ++;
         }
    
         if(this.pageNumber  < this.pages){
               this.pages =  this.pageNumber;
         }
       
         this.refreshItems();
         console.log("this.pageNumber :  "+this.pageNumber);
   }

   FilterByName(){
      this.filteredItems = [];
      if(this.inputName != ""){
            productList.forEach(element => {
                if(element.name.toUpperCase().indexOf(this.inputName.toUpperCase())>=0){
                  this.filteredItems.push(element);
               }
            });
      }else{
         this.filteredItems = productList;
      }
      console.log(this.filteredItems);
      this.init();
   }
   fillArray(): any{
      var obj = new Array();
      for(var index = this.pageStart; index< this.pageStart + this.pages; index ++) {
                  obj.push(index);
      }
      return obj;
   }
 refreshItems(){
               this.items = this.filteredItems.slice((this.currentIndex - 1)*this.pageSize, (this.currentIndex) * this.pageSize);
               this.pagesIndex =  this.fillArray();
   }
   prevPage(){
      if(this.currentIndex>1){
         this.currentIndex --;
      } 
      if(this.currentIndex < this.pageStart){
         this.pageStart = this.currentIndex;
      }
      this.refreshItems();
   }
   nextPage(){
      if(this.currentIndex < this.pageNumber){
            this.currentIndex ++;
      }
      if(this.currentIndex >= (this.pageStart + this.pages)){
         this.pageStart = this.currentIndex - this.pages + 1;
      }
 
      this.refreshItems();
   }
    setPage(index : number){
         this.currentIndex = index;
         this.refreshItems();
    }

 }

更新 app.module.ts

您应该更新此文件以导入 Pagination 组件,以便在 index.html 中可见。

import { NgModule} from '@angular/core';
import { FormsModule }   from '@angular/forms';
import { BrowserModule} from '@angular/platform-browser';
import { Pagination}   from './app.paginationComponent';

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

创建 index.html

这是一个 HTML 页面,我们将在此页面中包含运行分页组件所需的所有 js 文件和 css 样式。

<html>
  <head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="./css/styles.css">
    <link rel="stylesheet" href="./css/bootstrap.css">
    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
       
    </script>
  </head>
  <!-- 3. Display the application -->
  <body>
    <div class="container">
      <div class=" row">
        <h3>Angular2 : Table Pagination with search bar</h3>
      </div>
       <br>
      <div class=" row">
        <div class="col col-lg-6">
          <my-pagination>Loading...</my-pagination>
        </div> 
      </div>
    </div>
  </body>
</html>

**) 运行演示

要运行 Angular2 应用程序,您应该在应用程序的根文件夹中输入以下 cmd 命令行:

  • npm install :安装所需模块(可选)。
  • npm start :启动应用程序的构建。

最后,如果演示成功运行,您应该会看到以下渲染效果

如果用户从分页栏中选择一个页码,显示将如下所示

如果用户在搜索框中输入“Orange”文本并单击“Apply”按钮,搜索过程将给出

参考文献

关注点

我希望您喜欢这篇博文。请尝试下载源代码,我期待您的提问和评论。

历史

  • v1 2016/11/06:初始版本
© . All rights reserved.