Angular2とBootstrap3を使って一覧データをページングで表示するサンプルコードを作成しました。
※Angular2の2.0.0版、TypeScriptを使って確認したものです。(デモはv4.4.3、v2.0.0で動作確認)
Bootstrap3によるCSS設定、Angular2のビルトインパイプSliceなどの機能を使用していてコードが少し長くなっているので、2段階のステップに分けて作成しています。
※目次をクリックすると目次の下部にコンテンツが表示されます。
1ページ当りの表示件数を基にページ数を計算し、ページ数分のページリンクをBootstrap3のpagination属性を使って表示します。
①ページ数の計算
itemsPerPageがページ当りの件数で、配列データ数を割ってページ数を求めます。ページ数分のページ番号をリターンします。
public itemsPerPage: number = 3;
range() {
this._maxPage = Math.ceil(this.friends.length/this.itemsPerPage);
var ret = [];
for (var i=1; i<=this._maxPage; i++) {
ret.push(i);
}
return ret;
};
②Bootstrap3のpagination属性を使ってページリンク表示
Bootstrap3のページングの機能を使ってページリンクを表示します。
上記①で定義したrange()関数を使ってページ番号をリターンし、ページ番号のリンクを表示しています。
<ul class="pagination">
<li>
<a href="#step1" (click)="prevPage()">≪ 前へ</a>
</li>
<li *ngFor="let n of range()" (click)="setPage(n)">
<a href="#step1">{{n}}</a>
</li>
<li>
<a href="#step1" (click)="nextPage()">次へ ≫</a>
</li>
</ul>
2)リンククリック時の動作を定義
①現在表示しているページ番号を示す変数の初期値を定義
public currentPage: number = 1;
②ページ当りの表示個数
<input [(ngModel)]=”itemsPerPage” type=”number”>
③配列データを表示
現在のページ番号currentPageとページ当りの表示個数を指定して、指定したページのデータを表示します。
<tr *ngFor=”let item of friends | slice:(currentPage-1)*itemsPerPage:currentPage*itemsPerPage”>
※ビルトインパイプSliceの使用法についてはこちら。
④ページ番号リンククリック時の動作を定義
ページ番号をクリックするとcurrentPageにそのページ番号を設定します。これで上記③のオフセットが変更され、指定したページのデータを表示出来ます。
(テンプレート)
<li *ngFor="let n of range()" (click)="setPage(n)">
<a href="#">{{n}}</a>
</li>
(コンポーネントクラス)
setPage(n) {
this.currentPage = n;
};
⑤前後のページへのリンク押下時の動作定義
上記④と同様にcurrentPageの値を更新します。
(テンプレート)
<a href="#" (click)="prevPage()">≪ 前へ</a>
<a href="#" (click)="nextPage()">次へ ≫</a>
(コンポーネントクラス)
prevPage() {
if (this.currentPage > 1) {
--this.currentPage;
}
};
nextPage() {
if (this.currentPage < this._maxPage) {
++this.currentPage;
}
};
Angular2のng-classを使ってBootstrap3のpagenationのactive、disableを動的に設定して切替えます。
①現在表示しているページ番号のリンクをアクティブにする
Angular2のngClassディレクティブを使って、リンクのページ番号nと現在表示しているページ番号currentPageが等しい場合は、”active”のCSSクラスを動的に追加し、色を変更できます。
※ngClassディレクティブの使用方法はこちら。
<li *ngFor=”let n of range()”
[ngClass]=”{active: n === currentPage}”
(click)=”setPage(n)”>
②前後のページへのリンクの有効、無効を切替え
上記①と同様にngClassディレクティブを使って、現在のページが先頭または最後かどうかチェックし、マッチした場合は、”disabled”のCSSクラスを動的に追加し、リンクを無効にします。
(テンプレート)
<ul class="pagination">
<li [ngClass]="prevPageDisabled()">
<a href="#step2" (click)="prevPage()">≪ 前へ</a>
</li>
:
<li [ngClass]="nextPageDisabled()">
<a href="#step2" (click)="nextPage()">次へ ≫</a>
</li>
</ul>
(コンポーネントクラス)
prevPageDisabled() {
return this.currentPage === 1 ? "disabled" : "";
};
nextPageDisabled() {
return this.currentPage === this._maxPage ? "disabled" : "";
};
Bootstrap : 3.x
Loading…
<html>
<head>
<title>Angular 2 Demo</title>
<script src="https://npmcdn.com/core-js/client/shim.min.js"></script>
<script src="https://unpkg.com/zone.js@0.7.4?main=browser"></script>
<script src="https://npmcdn.com/systemjs@0.19.39/dist/system.src.js"></script>
<script src="./js/systemjs.config.js"></script>
<script>
System.import('./ts/app.ts').catch(function(err){ console.error(err); }); </script>
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/styles.css">
</head>
<body>
<div class="container">
<my-app>Loading...</my-app>
</div>
</body>
</html>
(systemjs.config.js)
(function (global) {
var ngVer = '@4.4.3';
System.config({
transpiler: 'ts',
typescriptOptions: {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"strict": true
},
meta: {
'typescript': {
"exports": "ts"
}
},
paths: {
'npm:': 'https://unpkg.com/'
},
map: {
'app': 'app',
'@angular/animations': 'npm:@angular/animations' + ngVer + '/bundles/animations.umd.js',
'@angular/animations/browser': 'npm:@angular/animations' + ngVer + '/bundles/animations-browser.umd.js',
'@angular/core': 'npm:@angular/core' + ngVer + '/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common' + ngVer + '/bundles/common.umd.js',
'@angular/common/http': 'npm:@angular/common' + ngVer + '/bundles/common-http.umd.js',
'@angular/compiler': 'npm:@angular/compiler' + ngVer + '/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser' + ngVer + '/bundles/platform-browser.umd.js',
'@angular/platform-browser/animations': 'npm:@angular/platform-browser' + ngVer + '/bundles/platform-browser-animations.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic' + ngVer + '/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http' + ngVer + '/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router' + ngVer + '/bundles/router.umd.js',
'@angular/router/upgrade': 'npm:@angular/router' + ngVer + '/bundles/router-upgrade.umd.js',
'@angular/forms': 'npm:@angular/forms' + ngVer + '/bundles/forms.umd.js',
'@angular/upgrade': 'npm:@angular/upgrade' + ngVer + '/bundles/upgrade.umd.js',
'@angular/upgrade/static': 'npm:@angular/upgrade' + ngVer + '/bundles/upgrade-static.umd.js',
// other libraries
'rxjs': 'npm:rxjs@5.0.1',
'tslib': 'npm:tslib/tslib.js',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
'ts': 'npm:plugin-typescript@5.2.7/lib/plugin.js',
'typescript': 'npm:typescript@2.3.2/lib/typescript.js',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.ts',
defaultExtension: 'ts',
meta: {
'./*.ts': {
loader: 'systemjs-angular-loader.js'
}
}
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
interface Friend {
id: number;
name: string;
age: number;
address: string;
}
@Component({
selector: 'my-app',
template: `
<strong id="step1">ステップ1)配列データをページングで表示</strong><br />
<form class="form-inline">
<div class="form-group">
<label>1ページの件数:</label>
<input [(ngModel)]="itemsPerPage" type="number"
[ngModelOptions]="{standalone: true}">
</div>
</form>
<table class="table table-striped">
<thead>
<tr>
<th>№</th><th>名前</th><th>年齢</th><th>住所</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of friends | slice:(currentPage-1)*itemsPerPage:currentPage*itemsPerPage">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{item.address}}</td>
</tr>
</tbody>
<tfoot>
<td colspan="4">
<ul class="pagination">
<li>
<a href="#step1" (click)="prevPage()">≪ 前へ</a>
</li>
<li *ngFor="let n of range()" (click)="setPage(n)">
<a href="#step1">{{n}}</a>
</li>
<li>
<a href="#step1" (click)="nextPage()">次へ ≫</a>
</li>
</ul>
</td>
</tfoot>
</table>
<strong id="step2">ステップ2)ページリンクのCSS設定</strong><br />
<form class="form-inline">
<div class="form-group">
<label>1ページの件数:</label>
<input [(ngModel)]="itemsPerPage" type="number"
[ngModelOptions]="{standalone: true}">
</div>
</form>
<table class="table table-striped">
<thead>
<tr>
<th>№</th><th>名前</th><th>年齢</th><th>住所</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of friends | slice:(currentPage-1)*itemsPerPage:currentPage*itemsPerPage">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{item.address}}</td>
</tr>
</tbody>
<tfoot>
<td colspan="4">
<ul class="pagination">
<li [ngClass]="prevPageDisabled()">
<a href="#step2" (click)="prevPage()">≪ 前へ</a>
</li>
<li *ngFor="let n of range()"
[ngClass]="{active: n === currentPage}"
(click)="setPage(n)">
<a href="#step2">{{n}}</a>
</li>
<li [ngClass]="nextPageDisabled()">
<a href="#step2" (click)="nextPage()">次へ ≫</a>
</li>
</ul>
</td>
</tfoot>
</table>
`
})
export class AppComponent {
public friends = FRIENDS;
public itemsPerPage: number = 3;
public currentPage: number = 1;
private _maxPage: number;
range() {
this._maxPage = Math.ceil(this.friends.length/this.itemsPerPage);
var ret = [];
for (var i=1; i<=this._maxPage; i++) {
ret.push(i);
}
return ret;
};
setPage(n) {
this.currentPage = n;
};
prevPage() {
if (this.currentPage > 1) {
--this.currentPage;
}
};
nextPage() {
if (this.currentPage < this._maxPage) {
++this.currentPage;
}
};
prevPageDisabled() {
return this.currentPage === 1 ? "disabled" : "";
};
nextPageDisabled() {
return this.currentPage === this._maxPage ? "disabled" : "";
};
}
@NgModule({
imports: [
BrowserModule,
FormsModule
],
declarations: [
AppComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);
var FRIENDS: Friend[] = [
{ id: 1, name: "相田", age: 20 ,address: "東京都品川区"},
{ id: 2, name: "伊藤", age: 55 ,address: "神奈川県横浜市"},
・・・・
];