BLOG

ブログ

【Angular】パイプ / ディレクティブについてまとめてみた

こんにちは、髙田です!

今回はAngularのテンプレートで使用するパイプとディレクティブについてまとめてみました!
最後まで見ていただけると嬉しいです✌

ではさっそく本題へGo!

パイプ / ディレクティブとは

パイプ
テンプレート内でデータを変換、または加工ができる機能。
例)日付のフォーマットや、テキストの大文字変換などがテンプレート内で可能になる。

ディレクティブ
ngIf・ngClassなどAngular独自の要素/属性を設定することで、DOMを変更する機能。
Angularには3種類のディレクティブがあります。

種類 概要
コンポーネントコンポーネントとして定義されるディレクティブ
構造ディレクティブDOMの構造を変更するディレクティブ(*ngIf・*ngFor)
属性ディレクティブDOMの外観や動作を変更するディレクティブ(ngClass・ngStyle)

具体的な機能についてはソースコードを交えて説明します!

パイプ

パイプの基本構文

{{ value | pipeName[:pipeArgument1[:pipeArgument2[...]]] }}
value変換したいデータ
pipeName使用するパイプの名前
pipeArgumentパイプに渡すオプションの配列(複数の引数を渡すことができます)

では実際に使用例をご紹介します。

日付/時刻を整形する

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<p>{{ today | date:'yyyy-MM-dd' }}</p>`
})
export class AppComponent {
  today: Date = new Date();
}

todayが2024年7月31日の場合、上記コードは以下のように表示されます。

<p>2024-07-31</p>

‘yyyy-MM-dd’の箇所をあらかじめ決められた書式型にしたり、日付文字列を指定することもできます。

fullDate(完全な日付)

<p>{{ today | date:'fullDate' }}</p>
<!-- 出力: 2024年7月31日水曜日 (例) -->

カスタムフォーマット

<p>{{ today | date:'yyyy/MM/dd HH:mm:ss' }}</p>
<!-- 出力: 2024/07/31 14:30:00 (例) -->

小文字大文字に変換

lowercase(小文字変換パイプ)

<p>{{ 'Hello World' | lowercase }}</p>
<!-- 出力: hello world -->

uppercase(大文字変換パイプ)

<p>{{ 'Hello World' | uppercase }}</p>
<!-- 出力: HELLO WORLD -->

パイプは他にも以下の種類があります。
ざっくりとした仕様をまとめておりますので、ご活用ください。

パイプ概要
titlecase単語の先頭文字を大文字に変換
slice配列や文字列の一部を抽出
number数値を桁区切り文字で整形
percentパーセント形式への変換
currency通過形式への変換
jsonオブジェクトをJSON形式に変換
i18nPlural数値に基づくメッセージを表示
i18nSelect文字列に基づくメッセージを表示
asyncObservable/Promiseによる非同期処理の結果を取得

ディレクティブ

今回は構造ディレクティブと属性ディレクティブについてご紹介いたします!

構造ディレクティブ

DOMの構造を変更するために使用されます。代表的な機能3つご紹介します。

ngIf条件に基づいて要素を表示/非表示切り替え
ngSwitch式の値によって表示を切り替え
ngForリストや配列を繰り返し表示

*ngIf

条件に基づいて要素を表示または非表示にします。

<div *ngIf="isVisible">この要素は表示されます。</div>

*ngSwitch

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div [ngSwitch]="userStatus">
      <div *ngSwitchCase="'online'">ユーザーはオンラインです。</div>
      <div *ngSwitchCase="'offline'">ユーザーはオフラインです。</div>
      <div *ngSwitchCase="'busy'">ユーザーは取り込み中です。</div>
      <div *ngSwitchDefault>ユーザーのステータスは不明です。</div>
    </div>
  `
})
export class AppComponent {
  userStatus: string = 'online'; // ここでステータスを設定
}

上記の場合、「ユーザーはオンラインです。」と表示されます。

[ngSwitch]評価する式を指定します。
*ngSwitchCase条件が一致する場合に表示するテンプレートを指定します。
*ngSwitchDefaultどの条件にも一致しない場合に表示するテンプレートを指定します。

*ngFor

リストや配列を繰り返し表示するときに使用されます。

<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

💡*(アスタリスク)について💡

*はテンプレートを<ng-template>要素に変換しますよ〜という意味を持ちます。
そのため、Angularのテンプレートコンパイラに対して、ディレクティブがテンプレートの一部を制御することを示しています。

属性ディレクティブ

属性ディレクティブは、要素のプロパティやスタイルを動的に変更することができます。
代表的な属性ディレクティブを3つご紹介します。

ngClassクラスの追加や削除を動的に行います。
ngStyleスタイルの追加や削除を動的に行います。
ngPlural数値に基づいて異なるテンプレートを表示する。

ngClass

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div [ngClass]="{'active': isActive, 'inactive': !isActive}">
      この要素は {{ isActive ? 'アクティブ' : '非アクティブ' }} です。
    </div>
    <button (click)="toggleActive()">切り替え</button>
  `,
  styles: [`
    .active {
      color: green;
    }
    .inactive {
      color: red;
    }
  `]
})
export class AppComponent {
  isActive: boolean = true;

  toggleActive() {
    this.isActive = !this.isActive;
  }
}

ngClass を使用して要素のクラスを動的に切り替えています。ボタンをクリックすることで、要素のクラスが active と inactive の間で切り替わり、それに応じてテキストの色も変わります。

ngStyle

HTML要素の[ngStyle]属性にオブジェクトや式をバインドして、スタイルを動的に変更することができます。いくつか例をご紹介します。

  • スタイルプロパティとその値をオブジェクトとして直接指定する方法。
<div [ngStyle]="{'color': 'red', 'font-size': '20px'}">
  サンプル
</div>
  • コンポーネントのプロパティを設定する方法。
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div [ngStyle]="{'color': textColor, 'font-size': fontSize + 'px'}">
      サンプル
    </div>
  `
})
export class AppComponent {
  textColor = 'blue';
  fontSize = 16;
}
  • 条件に基づいてスタイルを変更することもできます。
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div [ngStyle]="isSpecial ? specialStyles : normalStyles">
      サンプル
    </div>
  `
})
export class AppComponent {
  isSpecial = true;
  specialStyles = {
    'color': 'red',
    'font-weight': 'bold'
  };
  normalStyles = {
    'color': 'black',
    'font-weight': 'normal'
  };
}

ngPlural

ngPluralは、数値に基づいて異なるテンプレートを表示するために使用されます。特定の数値に対して異なるメッセージやコンテンツを表示する場合に便利です。

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div [ngPlural]="value">
      <ng-template ngPluralCase="=0">There are no items.</ng-template>
      <ng-template ngPluralCase="=1">There is one item.</ng-template>
      <ng-template ngPluralCase="other">There are many items.</ng-template>
    </div>
    <button (click)="decrement()">-</button>
    <span>{{ value }}</span>
    <button (click)="increment()">+</button>
  `
})
export class AppComponent {
  value: number = 0;

  increment() {
    this.value++;
  }

  decrement() {
    if (this.value > 0) {
      this.value--;
    }
  }
}

  • ngPlural: 数値を受け取り、その数値に基づいて適切なテンプレートを選択します。
  • ngPluralCase: 特定の数値または範囲に対して表示するテンプレートを定義します。ngPluralCase は以下のような形式で使用されます:
    • =0: 数値が0の場合に表示されるテンプレート。
    • =1: 数値が1の場合に表示されるテンプレート。
    • other: 上記のいずれにも該当しない場合に表示されるテンプレート。

さいごに

いかがでしたでしょうか!今後もAngularの記事を少しずつ書いていこうかなと思っているので、ご覧いただけると嬉しいです!

ありがとうございました〜!

RELATED ARTICLE