AngularのPipe
(Angular v.4.3.6を利用)
- これは何か
- 概要
- Built-in
- カスタムパイプ
- Change detection
- Impure pipes
- AsyncPipe
- ServiceやComponent内でも利用したい
- DatePipeのlocaleを変更したい場合
- その他
これは何か
Angular (4+)を始めたのでドキュメントを読んでいます。今回はPipeについて。
内容は以下ドキュメントからの抜粋のようなものです。
概要
- PipeはHtmlテンプレート内でデータを意図した形式に変換する仕組み
<p>The hero's birthday is {{ birthday | date:"MM/dd/yy" }} </p>
Built-in
カスタムパイプ
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'custom' }) export class CustomPipe implements PipeTransform { transform(value: any, args?: any): any { return null; } }
- Style Guide的にはShared feature moduleに入れる
Change detection
- Pipeは通常のChange detectionと仕様が異なる
- 例えば、配列に要素を追加しただけではPipeは実行されない
- 参照を変更する必要がある。新しい配列で置き換えるた場合、Pipeは実行される
<!-- heroが追加されれば新しいhero.nameが表示される --> <div *ngFor="let hero of heroes"> {{hero.name}} </div> <!-- heroが追加されても表示は変わらない --> <div *ngFor="let hero of (heroes | fooPipe)"> {{hero.name}} </div>
上記のような場合の対応策
- impure pipeにする
- Pipeを利用しないでComponent内で処理をする
The Angular team and many experienced Angular developers strongly recommend moving filtering and sorting logic into the component itself
Impure pipes
pure: false
にする
@Pipe({ name: 'fooImpure', pure: false }) export class FooImpurePipe extends FooPipe { }
- pure pipeはpure changeを見つけたときに実行される
A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).
- impure pipeの場合
Angular executes an impure pipe during every component change detection cycle. An impure pipe is called often, as often as every keystroke or mouse-move.
AsyncPipe
- Built-in pipe
- impure pipeの参考になる
Promise
やObservable
を入力値として受け取る- 詳細はコードを見た方がはやい
ServiceやComponent内でも利用したい
- Angular 2/4 use pipes in services and components - Stack Overflow
- DIを利用する
- providersに登録する必要がある
import { DatePipe } from '@angular/common'; class MyService { constructor(private datePipe: DatePipe) {} transformDate(date) { this.datePipe.transform(myDate, 'yyyy-MM-dd'); } }
DatePipeのlocaleを変更したい場合
その他
- Pipeをつなげることも可能
{{ birthday | date | uppercase}}
- AngularJSに実装されていた
filter
,orderBy
などがない理由- https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
- パフォーマンスの問題
- Minifyされたコードで実行保証ができないことがあるため