2017.05.31
ionicでPipeを使ってみる
変数を見せるようにPipeを使用して変更してみます。
今回は、booleanのものを「true」なら「同意する」、「false」なら「同意しない」を表示させてみます。
実装
まずはPipeを作成します。
コマンド:ionic g pipe [Pipe名]
pipesフォルダが作成されてその中にpipeが作成されています。
booleanの変数を「同意する」または「同意しない」に変更するようにtransformメソッドを以下のように書き換えます。
import { Pipe, PipeTransform } from '@angular/core';
/**
* Generated class for the AgreePipe pipe.
*
* See https://angular.io/docs/ts/latest/guide/pipes.html for more info on
* Angular Pipes.
*/
@Pipe({
name: 'agree',
})
export class AgreePipe implements PipeTransform {
/**
* Takes a value and makes it lowercase.
*/
transform(value: boolean) {
if(value) {
return '同意する';
} else {
return '同意しない';
}
}
}
home.htmlでPipeを使用します。
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
{{ check | agree }}
</ion-content>
home.tsに変数を準備します。
とりあえずtrueにしておきます。
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
check:boolean;
constructor(public navCtrl: NavController) {
this.check = true;
}
}
実行
実装が完了したのでionic serveで実行してみます。
home.tsのcheckをfalseにして実行してみます。
しっかりとbooleanが変換されて「同意する」、「同意しない」に変更することができました。




