Angular4にはAngular1系のFilterの代わりにPipeという機能があります。
デフォルトでは以下のパイプが存在します。
- DatePipe(日付)
- UpperCasePipe(大文字)
- LowerCasePipe(小文字)
- CurrencyPipe(通貨)
- PercentPipe(パーセント) https://angular.io/guide/pipes#built-in-pipes
つまり上記以外はカスタムパイプとして自分で作らなきゃいけないんですね。
Filterの頃はソートとかあったのですが、そういうのも自分で作らないといけないです。めんどくさ。
参考・カスタムパイプ
https://angular.io/guide/pipes#custom-pipes
パイプの定義とかはあんまわかってないので、公式ドキュメントとか見てください。
スタックオーバーフローでパクってきたソート(降順)のPipeを置いておきます。
適当にいじって使ってみてください。
order-by-pipe.ts
import { PipeTransform, Pipe } from '@angular/core';
// 配列をObjectのKeyの降順でソートするパイプ
@Pipe({
name: "orderBy"
})
export class OrderByPipe implements PipeTransform {
transform(array: any[], field: string): any[] {
if(array && array.length > 0) {
array.sort((a: any, b: any) => {
if (a[field] > b[field]) {
return -1;
} else if (a[field] < b[field]) {
return 1;
} else {
return 0;
}
});
}
return array;
}
}
テンプレートでは以下のように書きます。
今回はIonicの例。
test-template.html
<ion-list>
<ion-item *ngFor="let object of objectArray | orderBy:'price'">
<ion-avatar item-start>
<img src="assets/images/{{ object.imageName }}">
</ion-avatar>
<h2>{{ object.name }}</h2>
<p>{{ object.price }}</p>
</ion-item>
</ion-list>
上記のobjectArrayの中身はこんな感じかな。
object.ts
let objectArray = [
{
'name':'ボールペン',
'price':100
},
{
'name':'鉛筆',
'price':60
},
{
'name':'消しゴム',
'price':120
},
];
ちなみにapp.module.tsにも書いておかないと動かないっす。
パイプを置いてある場所からimportして、NgModuleのdeclarationsにも追記します。
app.module.ts
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
// 画面
import { DetailPage } from '../pages/detail/detail';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
// カスタムパイプ
import { OrderByPipe } from '../utilities/order-by-pipe';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
@NgModule({
declarations: [
MyApp,
DetailPage,
HomePage,
TabsPage,
OrderByPipe,
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
DetailPage,
HomePage,
TabsPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}