AngularのPipe

(Angular v.4.3.6を利用)

これは何か

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 pipepure 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

ServiceやComponent内でも利用したい

import { DatePipe } from '@angular/common';
class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    this.datePipe.transform(myDate, 'yyyy-MM-dd');
  }
}

DatePipeのlocaleを変更したい場合

その他