Angular2では、Date、Decimal、Currency、Json、Sliceといったビルトインパイプが用意されていますが、自分でパイプを定義することもできます。Angular1で提供されていたorderByがAngular2のビルトインパイプには含まれていなかったたため、ソートを行うパイプをサンプルとして作成してみました。
※Angular2の2.0.0版、TypeScriptを使って確認したものです。(デモはv4.4.3、v2.0.0で動作確認)
※目次をクリックすると目次の下部にコンテンツが表示されます。
カスタムパイプの作成方法
ソートを行うパイプを例にカスタムパイプの作成方法を示します。
1)仕様
・パイプのクラス名:OrderbyPipe
・パイプ名:orderby
・ソート対象のデータ:”products”という名前の配列
name price
商品A 500
商品B 300
商品E 800
・パイプの使用方法
“orderby: key”の”key”で指定した配列要素をキーとして配列データをソート
<tr *ngFor=”let item of products | orderby: key>
<td>{{item.name}}</td>
<td>{{item.price | currency:’JPY’:true}}</td>
</tr>
2)作成方法
①Pipe、PipeTransformをAngular2のコアからインポート
import {Pipe, PipeTransform} from ‘@angular/core’;
②@Pipeデコレーターのname属性でテンプレート内で指定するパイプ名を定義
@Pipe({name: ‘orderby’})
③@Pipeメタデータでデコレートしてパイプ用のクラスを定義
@Pipe({name: ‘orderby’})
export class OrderbyPipe implements PipeTransform {
transform(array: Array<object>, key:string): Array<object> {
・・・
・パイプ用のクラスは”PipeTransform”インターフェースの”transeform”メソッドを実装し、パイプで操作する内容を定義する。
・”PipeTransform”インターフェースの最初の引数はパイプの操作対象のデータ(サンプルでは”products”配列)、二番目の引数は、パイプ名:・・・の部分に指定したオプション(サンプルではorderby: keyの”key”)となる。
3)パイプの利用方法
@Componentデコレーターの”pipes”属性で配列としてカスタムパイプを指定する。ビルトインパイプの場合は事前に登録されているので必要ないがカスタムパイプの場合は明示的に指定する必要がある。
1)仕様
・パイプのクラス名:OrderbyPipe
・パイプ名:orderby
・ソート対象のデータ:”products”という名前の配列
name price
商品A 500
商品B 300
商品E 800
・パイプの使用方法
“orderby: key”の”key”で指定した配列要素をキーとして配列データをソート
<tr *ngFor=”let item of products | orderby: key>
<td>{{item.name}}</td>
<td>{{item.price | currency:’JPY’:true}}</td>
</tr>
2)作成方法
①Pipe、PipeTransformをAngular2のコアからインポート
import {Pipe, PipeTransform} from ‘@angular/core’;
②@Pipeデコレーターのname属性でテンプレート内で指定するパイプ名を定義
@Pipe({name: ‘orderby’})
③@Pipeメタデータでデコレートしてパイプ用のクラスを定義
@Pipe({name: ‘orderby’})
export class OrderbyPipe implements PipeTransform {
transform(array: Array<object>, key:string): Array<object> {
・・・
・パイプ用のクラスは”PipeTransform”インターフェースの”transeform”メソッドを実装し、パイプで操作する内容を定義する。
・”PipeTransform”インターフェースの最初の引数はパイプの操作対象のデータ(サンプルでは”products”配列)、二番目の引数は、パイプ名:・・・の部分に指定したオプション(サンプルではorderby: keyの”key”)となる。
3)パイプの利用方法
@Componentデコレーターの”pipes”属性で配列としてカスタムパイプを指定する。ビルトインパイプの場合は事前に登録されているので必要ないがカスタムパイプの場合は明示的に指定する必要がある。
@Component({
selector: 'my-app',
template: `
・・・
<tr *ngFor="let item of products | orderby: key | slice:0:5">
<td>{{item.name}}</td>
<td>{{item.price | currency:'JPY':true}}</td>
</tr>
・・・
`,
pipes: [OrderbyPipe]
})
デモ
Angular : 4.4.3(2.0.0でも動作確認済み)
Bootstrap : 3.x
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 { OrderbyPipe } from './orderby.pipe.ts'; class Product { name: string; price: number; } @Component({ selector: 'my-app', template: ` <table class="table"> <thead> <tr><th>商品名</th><th>価格</th></tr> </thead> <tbody> <tr *ngFor="let item of products | orderby: key"> <td>{{item.name}}</td> <td>{{item.price | currency:'JPY':true}}</td> </tr> </tbody> </table> `, pipes: [OrderbyPipe] }) export class AppComponent { public products = PRODUCTS; public key:string = 'price'; } @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent, OrderbyPipe ], bootstrap: [ AppComponent ] }) export class AppModule { } platformBrowserDynamic().bootstrapModule(AppModule); var PRODUCTS: Product[] = [ { name: "デジタルカメラA",price: 8500}, { name: "デジタルカメラD",price: 3500}, { name: "パソコンB" ,price: 15900}, { name: "デジタルカメラB",price: 9800}, { name: "パソコンD" ,price: 5900}, { name: "パソコンC" ,price: 25900}, { name: "パソコンA" ,price: 14900} ]; (カスタムパイプorderby.pipe.ts)
import {Pipe, PipeTransform} from '@angular/core'; @Pipe({name: 'orderby'}) export class OrderbyPipe implements PipeTransform { transform(array: Array, key:string): Array { array.sort((a: object, b: object) => { if (a[key] b[key]) { return 1; } else { return 0; } }); return array; } }