Skip to content

Angular チートシート

Google が開発する TypeScript ベースの Web アプリケーションフレームワーク。

01

はじめに

CLI のセットアップとプロジェクト作成

Angular CLI が開発の主ツールです。ng new でルーティングとスタイリングが事前設定された完全なプロジェクトをスキャフォールドできます。一貫したファイル生成には ng generate(ng g)を使います。ビルド・テスト・デプロイも CLI が担います。

angular
# install Angular CLI globally
npm install -g @angular/cli

# create a new project
ng new my-app --routing --style=scss
cd my-app

# serve the app (default: localhost:4200)
ng serve --open

# generate components, services, etc.
ng generate component components/user-profile
ng g service services/auth
ng g module modules/admin --routing

プロジェクト構成の概要

Angular は明確なフォルダ構成を強制します。src/app にすべての機能コードを置き、main.ts でルートコンポーネントをブートストラップします。angular.json にはビルド・テスト・サーブの設定を記述します。environments フォルダで環境ごとに API URL を切り替えられます。

angular
my-app/
├── src/
│   ├── app/                 # application code lives here
│   │   ├── app.component.ts
│   │   ├── app.component.html
│   │   └── app.config.ts    # standalone bootstrap config
│   ├── assets/              # static images, fonts
│   ├── environments/        # env-specific values
│   ├── index.html           # main HTML entry
│   ├── main.ts              # bootstrap entry point
│   └── styles.scss          # global styles
├── angular.json             # CLI workspace config
├── package.json
└── tsconfig.json

サーブとビルド

ng serve はデフォルトでポート 4200 に HMR 風のリロード付き開発サーバーを起動します。本番ビルドでは tree-shaking・圧縮・ファイル名ハッシュ化によりキャッシュに対応します。肥大化した依存関係の調査には --stats-json と webpack-bundle-analyzer を使用します。ng test はデフォルトで Karma を実行します。

angular
# dev server with live reload
ng serve --port 4300 --open

# production build (outputs to dist/)
ng build --configuration production

# analyze bundle size
ng build --stats-json
npx webpack-bundle-analyzer dist/my-app/stats.json

# run unit tests (Karma + Jasmine)
ng test

# run end-to-end tests
ng e2e

コード生成(Schematics)

Schematics によりファイル命名やボイラープレートを一貫させられます。--standalone フラグでスタンドアロンコンポーネントを生成できます(v17 以降は推奨)。--route + --module で遅延ロードされるルートを自動で接続します。--functional で作ったガードはクラスの代わりに関数を返します。

angular
# generate a standalone component
ng g component user-profile --standalone

# generate a service with root provider
ng g service services/auth

# generate a guard (functional by default)
ng g guard guards/auth --functional

# generate a pipe, directive, or module
ng g pipe pipes/shorten
ng g directive directives/highlight
ng g module admin --routing --route admin --module app

# generate an interface or enum
ng g interface models/user
ng g enum models/role

設定(angular.json)

angular.json はワークスペースの設定ファイルです。各プロジェクトには build・serve・test・lint のターゲットがあります。budgets はバンドルサイズがしきい値を超えると警告またはエラーを出します。polyfills 配列には Angular が必要とする zone.js を含めます。1 つのワークスペースに複数プロジェクト(アプリ + ライブラリ)を共存させられます。

angular
{
  "projects": {
    "my-app": {
      "architect": {
        "build": {
          "options": {
            "outputPath": "dist/my-app",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": ["zone.js"],
            "tsConfig": "tsconfig.app.json",
            "assets": ["src/favicon.ico", "src/assets"],
            "styles": ["src/styles.scss"],
            "scripts": []
          },
          "configurations": {
            "production": {
              "budgets": [{ "type": "initial", "maximumWarning": "500kb" }]
            }
          }
        }
      }
    }
  }
}

環境(Environments)

Angular はビルド時の設定(dev と prod など)に応じて環境ファイルを差し替えます。ファイルの差し替えは angular.json の fileReplacements で設定します。environment オブジェクトを注入すれば、URL をハードコードせずに環境固有の値へアクセスできます。本物のシークレットをリポジトリにコミットしてはいけません。

angular
// src/environments/environment.ts
export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000/api',
  apiKey: 'dev-key'
};

// src/environments/environment.prod.ts
export const environment = {
  production: true,
  apiUrl: 'https://api.example.com',
  apiKey: 'prod-key'
};

// usage in a service
import { environment } from '../environments/environment';

@Injectable({ providedIn: 'root' })
export class ApiService {
  private baseUrl = environment.apiUrl;
}
02

コンポーネントの基本

基本のコンポーネント

コンポーネントは @Component でデコレートされた TypeScript クラスです。selector はテンプレートで使うカスタム HTML タグです。templateUrl/styleUrls は外部ファイルを参照し、インラインなら template/styles を使います。@Input は親からバインド可能なプロパティを示します。コンポーネントは 1 つの責務に絞りましょう。

angular
// user-profile.component.ts
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.scss'],
})
export class UserProfileComponent {
  @Input() name = 'Guest';
  @Input() age = 0;

  greet() {
    return `Hello, ${this.name}!`;
  }
}

インラインテンプレートのコンポーネント

インラインテンプレートは小さなコンポーネントに便利で、余計なファイルも増やしません。複数行文字列にはバッククォートを使い、内部のバッククォートは \` でエスケープします。styles は CSS 文字列の配列を受け付けます。:host セレクタでコンポーネント自身の要素を対象にできます。テンプレートが 10 行程度を超えたら外部ファイルに分けましょう。

angular
@Component({
  selector: 'app-counter',
  template: `
    <button (click)="decrement()">-</button>
    <span>{{ count }}</span>
    <button (click)="increment()">+</button>
  `,
  styles: [`
    :host { display: flex; gap: 8px; align-items: center; }
    button { padding: 4px 12px; }
  `],
})
export class CounterComponent {
  count = 0;
  increment() { this.count++; }
  decrement() { this.count--; }
}

スタンドアロンコンポーネント(v14+)

スタンドアロンコンポーネントは NgModule を必要とせず、依存関係(CommonModule、FormsModule、他のコンポーネントなど)を列挙した独自の imports 配列を持ちます。これがモダンな推奨アプローチです。使用するものだけをインポートして tree-shaking を改善しましょう。main.ts で直接ブートストラップできます。

angular
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-search',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <input [(ngModel)]="query" placeholder="Search..." />
    <p>Searching for: {{ query }}</p>
  `,
})
export class SearchComponent {
  query = '';
}

Inputs と Outputs

@Input は親がプロパティバインディング経由でデータを渡せるようにします。@Output は EventEmitter を公開し、親はイベントバインディング経由で購読します。undefined エラーを避けるため、入力には必ずデフォルト値を設定しましょう。v17+ では新しい input()/output() シグナル API を使うとコードがすっきりします。

angular
@Component({
  selector: 'app-toggle',
  template: `
    <button (click)="toggle()">{{ label }}: {{ on ? 'On' : 'Off' }}</button>
  `,
})
export class ToggleComponent {
  @Input() label = 'Toggle';
  @Input() on = false;
  @Output() changed = new EventEmitter<boolean>();

  toggle() {
    this.on = !this.on;
    this.changed.emit(this.on);
  }
}

<!-- parent template -->
<app-toggle [label]="'Power'" [on]="isOn" (changed)="onToggle($event)" />

シグナルベースの入力(v17.1+)

input() 関数は関数のように呼び出せる読み取り専用のシグナル入力を作ります。input.required<T>() による必須入力や変換(transform)をサポートし、computed() や effect() ともシームレスに連携します。output() は @Output EventEmitter のモダンな代替です。これが Angular コンポーネント API の未来です。

angular
import { Component, input, output } from '@angular/core';

@Component({
  selector: 'app-card',
  template: `
    <div>{{ title() }} - {{ count() }}</div>
    <button (click)="clicked.emit()">Click</button>
  `,
})
export class CardComponent {
  // readonly signal inputs with defaults
  title = input<string>('Default');
  count = input<number>(0);

  // output() function replaces @Output
  clicked = output<void>();

  // computed derived from inputs
  // requires import { computed }
  // label = computed(() => this.title().toUpperCase());
}

ビューのカプセル化

Emulated(デフォルト)は一意な属性を付与してスタイルをコンポーネントにスコープします(実際の Shadow DOM は使わない)。None はスタイルをグローバルにします(控えめに使用)。ShadowDom はネイティブ Shadow DOM で真の分離を実現しますが、スタイルの侵入や一部のサードパーティライブラリに影響します。特別な理由がなければ Emulated を使いましょう。

angular
@Component({
  selector: 'app-styles',
  template: `<p class="local">Emulated (default)</p>`,
  styles: [`p.local { color: red; }`],
  encapsulation: ViewEncapsulation.Emulated, // default
})
export class StylesComponent {}

// ViewEncapsulation.None    -> styles leak globally
// ViewEncapsulation.ShadowDom -> real Shadow DOM (strong isolation)
// ViewEncapsulation.Emulated -> scoped attributes (default, recommended)
03

テンプレート構文

テキスト補間

二重波括弧 {{ }} は式を HTML エスケープしたテキストとして描画します。算術演算、三項演算子、メソッド呼び出し、プロパティアクセスなど、ほとんどの JS 式が使えます。new、typeof、代入演算子は使えません。パイプ(|)で出力を変換できます。補間は変更検知サイクルごとに再評価されます。

angular
<p>{{ title }}</p>                       <!-- renders the value -->
<p>{{ 1 + 2 }}</p>                        <!-- expressions allowed -->
<p>{{ user.name }}</p>                    <!-- property access -->
<p>{{ items.length }}</p>                 <!-- method/property -->
<p>{{ price | currency:'USD' }}</p>       <!-- pipe in interpolation -->
<p>{{ isReady ? 'Yes' : 'No' }}</p>       <!-- ternary -->

<!-- one-time interpolation updates when the source changes -->
<!-- new control flow @if, @for work without *ngIf/*ngFor directives -->

プロパティバインディングと属性バインディング

[prop] は DOM プロパティにバインドします(推奨)。[attr.name] は DOM プロパティが存在しない場合(colspan、SVG 属性など)に HTML 属性へバインドします。[class.x] は真偽値で 1 つのクラスをトグルし、[style.prop] は .px や % などの単位サフィックス付きでスタイルを設定します。信頼できないコンテンツを innerHTML にバインドするのは避けましょう。

angular
<!-- property binding: [prop]="expression" -->
<img [src]="user.avatar" [alt]="user.name" />
<button [disabled]="isSaving">Save</button>
<my-comp [data]="items"></my-comp>

<!-- attribute binding (for attrs without DOM props) -->
<td [attr.colspan]="2">Merged cell</td>
<svg [attr.viewBox]="box"></svg>

<!-- class & style binding -->
<div [class.active]="isActive">Active?</div>
<div [class]="dynamicClassString">
<div [style.color]="colorVar">
<div [style.width.px]="size">Width</div>

イベントバインディング

(event) は DOM イベントとカスタム EventEmitter の出力にバインドします。$event はイベントのペイロードです(ネイティブイベントでは DOM Event、カスタムでは emit された値)。.enter、.esc、.prevent、.stop などのイベント修飾子でイベントをフィルタ・変換できます。括弧内のターゲットがハンドラの発火条件を決めます。

angular
<button (click)="save()">Save</button>
<input (input)="onInput($event)" (keyup)="onKey($event)" />
<div (mouseenter)="hover=true" (mouseleave)="hover=false">Hover</div>

<!-- $event is the DOM event object -->
<input (keyup.enter)="submit()" (keyup.esc)="cancel()" />

<!-- passive events (scroll, touchmove) -->
<div (scroll.passive)="onScroll($event)">...</div>

<!-- binding to custom component outputs -->
<app-child (changed)="onChanged($event)"></app-child>

テンプレート参照変数

#var(または ref-var)は宣言された DOM 要素やコンポーネントインスタンスへの参照です。テンプレート内のどこからでもアクセスできます。コンポーネントならインスタンスが、要素なら HTMLElement が値になります。@for の内側では $index、$first、$last、$even、$odd という暗黙のコンテキスト変数が使えます。

angular
<input #nameInput type="text" />
<button (click)="nameInput.focus()">Focus</button>
<p>You typed: {{ nameInput.value }}</p>

<!-- ref to a component instance -->
<app-form #f="appForm"></app-form>
<button [disabled]="!f.valid" (click)="f.submit()">Submit</button>

<!-- ref inside @for -->
<ul>
  @for (item of items; track item.id) {
    <li>{{ item.name }} (index: {{ $index }})</li>
  }
</ul>

双方向バインディング(バナナインボックス)

[(ngModel)] には FormsModule が必要です。[(x)] 構文は [x] + (xChange) に展開されるため、カスタム双方向バインディングには x という名前の入力と xChange という名前の出力が必要です。「バナナ・イン・ア・ボックス」の語呂を思い出しましょう — 括弧が角括弧の内側に来ます。v17.2+ では model() シグナル関数で簡潔に書けます。

angular
<!-- [()] = "banana in a box" - property + event combined -->
<input [(ngModel)]="username" />

<!-- equivalent to -->
<input [ngModel]="username" (ngModelChange)="username = $event" />

<!-- two-way binding on custom components -->
<app-counter [(value)]="count"></app-counter>
<!-- requires: @Input() value; @Output() valueChange = new EventEmitter() -->

<!-- signals: model() for two-way (v17.2+) -->
// value = model<number>(0);

セーフナビゲーションと非 NULL アサーション

?. 演算子は nullable なチェーンを安全にたどり、例外の代わりに undefined を返します。まだ読み込まれていない非同期データに使えます。! 演算子はコンパイル時のアサーションにすぎず、実行時チェックは追加されないので、確信があるときだけ使いましょう。null になり得る配列には ?? [] をフォールバックとして使えます。

angular
<!-- safe navigation: short-circuits to undefined if null -->
<p>{{ user?.profile?.bio }}</p>
<p>{{ user?.getName?.() }}</p>

<!-- non-null assertion: tells compiler it's not null -->
<p>{{ user!.name }}</p>

<!-- in property bindings -->
<img [src]="user?.avatar" />
<app-detail [data]="user!"></app-detail>

<!-- safe navigation in @for doesn't replace track -->
@for (item of items ?? []; track item.id) { ... }
04

ディレクティブ

@if / @else(新しい制御フロー)

新しい @if/@else if/@else ブロック構文は *ngIf を置き換えます。CommonModule や NgIf のインポートが不要で、アスタリスクも不要です。さらに @else がネイティブに動作します(ngIf の ng-template ハックと違って)。新規コードにはこの構文が推奨されます。v17 で導入された組み込み制御フローの一部で、v18 で安定しています。

angular
@if (user) {
  <p>Hello, {{ user.name }}</p>
} @else if (loading) {
  <p>Loading...</p>
} @else {
  <p>No user found.</p>
}

<!-- no structural directive import needed, no * prefix -->
<!-- works in standalone templates automatically (v17+) -->

@for / @empty(新しい制御フロー)

@for は *ngFor を置き換え、効率的な DOM 差分更新のために track 式が必須です。@empty はコレクションが空のときのフォールバックを描画します。暗黙のコンテキスト変数($index、$first、$last など)は常に使えます。大きなリストのパフォーマンスには、安定した一意の id による track が極めて重要です。

angular
<ul>
  @for (item of items; track item.id) {
    <li>{{ item.name }} ({{ $index }})</li>
  } @empty {
    <li>No items yet.</li>
  }
</ul>

<!-- 'track' is REQUIRED for performance -->
<!-- implicit vars: $index, $first, $last, $even, $odd, $count -->

<!-- @for over a range -->
@for (i of [1,2,3,4,5]; track i) {
  <span>{{ i }}</span>
}

ngClass と ngStyle

ngClass はオブジェクト(真と評価されたキーが適用される)・配列・文字列を受け付けます。ngStyle は camelCase または kebab-case のキーを持つオブジェクトに単位サフィックスを付けて使えます。CommonModule または各ディレクティブのインポートが必要です。単一のクラス/スタイルなら [class.x] と [style.x] の方が軽量でインポートも不要です。

angular
<div [ngClass]="{ active: isActive, disabled: !enabled }">Box</div>
<div [ngClass]="['card', 'shadow', themeClass]">Card</div>
<div [ngClass]="currentClass">String</div>

<div [ngStyle]="{ color: textColor, 'font-size.px': size }">Text</div>
<div [ngStyle]="styleObject">Styled</div>

<!-- import CommonModule (or NgClass/NgStyle) for these -->
<!-- prefer [class.x] and [style.x] for single value bindings -->

@switch(新しい制御フロー)

@switch は *ngSwitch(および ngSwitchCase/ngSwitchDefault ディレクティブ)を置き換えます。ラップ用コンテナもインポートも不要で、すっきり書けます。各 @case は値が @switch 式に一致したときだけ描画され、@default がフォールバックです。v17+ で使える組み込み制御フローです。

angular
@switch (status) {
  @case ('loading') {
    <spinner>Loading...</spinner>
  }
  @case ('error') {
    <p class="error">Something went wrong</p>
  }
  @case ('success') {
    <p>Done!</p>
  }
  @default {
    <p>Idle</p>
  }
}

カスタム属性ディレクティブ

属性ディレクティブは DOM 要素の見た目や振る舞いを変更します。selector の [ブラケット] が属性としての使用にマッチします。ElementRef で DOM に直接アクセスし、HostListener で DOM イベントにバインドします。型安全のため ElementRef<HTMLElement> を注入しましょう。サーバーサイドレンダリング環境での DOM 操作には Renderer2 を推奨します。

angular
import { Directive, ElementRef, Input, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
})
export class HighlightDirective {
  @Input('appHighlight') highlightColor = 'yellow';

  constructor(private el: ElementRef<HTMLElement>) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.el.nativeElement.style.backgroundColor = this.highlightColor;
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.el.nativeElement.style.backgroundColor = '';
  }
}

<!-- usage: <p appHighlight="lightblue">Hover me</p> -->

構造ディレクティブの内部構造

構造ディレクティブは TemplateRef(ラップされたテンプレート)と ViewContainerRef(挿入先)を通じて DOM ノードを追加・削除します。アスタリスク(*)は要素を <ng-template> で包む糖衣構文です。新しい @if/@for/@switch ブロックが多くのカスタム構造ディレクティブを置き換えますが、このパターンは高度なケースでまだ有用です。

angular
import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';

@Directive({ selector: '[appUnless]' })
export class UnlessDirective {
  private hasView = false;

  @Input() set appUnless(condition: boolean) {
    if (!condition && !this.hasView) {
      this.vc.createEmbeddedView(this.tpl);
      this.hasView = true;
    } else if (condition && this.hasView) {
      this.vc.clear();
      this.hasView = false;
    }
  }

  constructor(private tpl: TemplateRef<unknown>, private vc: ViewContainerRef) {}
}

<!-- usage: <div *appUnless="hide">Shown when hide is false</div> -->
05

パイプ

組み込みパイプ

パイプはテンプレートの表示値を変換します。主な組み込みパイプ:date、number、currency、percent、uppercase、lowercase、titlecase、slice、json、async。パイプはデフォルトで純粋(pure)であり、入力の参照が変わったときだけ再計算します。書式文字列は Angular のロケール対応ルールに従います。

angular
<!-- date formatting -->
<p>{{ today | date }}</p>                          <!-- Sep 10, 2024 -->
<p>{{ today | date:'short' }}</p>
<p>{{ today | date:'yyyy-MM-dd HH:mm' }}</p>

<!-- number & currency -->
<p>{{ 3.14159 | number:'1.2-2' }}</p>               <!-- 3.14 -->
<p>{{ price | currency:'USD':'symbol':'1.2-2' }}</p>
<p>{{ ratio | percent }}</p>

<!-- text transforms -->
<p>{{ 'hello world' | uppercase }}</p>              <!-- HELLO WORLD -->
<p>{{ 'HELLO' | lowercase }}</p>
<p>{{ title | titlecase }}</p>
<p>{{ 'a/b/c' | slice:0:2 }}</p>

<!-- json (for debugging) -->
<pre>{{ obj | json }}</pre>

パイプの連結と引数

パイプは左から右へ連結され、各パイプは前段の出力を受け取ります。引数はコロン区切りで位置によって意味が決まります。書式化やフィルタリングのような純粋な変換に使い、テンプレートを宣言的に保ちましょう。パフォーマンスが重要なデータには非純粋(impure)パイプを避け、コンポーネント側で計算してください。

angular
<!-- chain: left to right, output of one feeds the next -->
<p>{{ '  hello  ' | trim | uppercase }}</p>         <!-- HELLO -->
<p>{{ birthday | date:'fullDate' | uppercase }}</p>
<p>{{ items | slice:0:3 | json }}</p>

<!-- parameters separated by colons -->
<p>{{ amount | number:'1.2-2':'en-US' }}</p>
<p>{{ meeting | date:'shortTime' }}</p>
<p>{{ list | slice:1:5 }}</p>

<!-- multiple parameters -->
<p>{{ value | myPipe:arg1:arg2:arg3 }}</p>

カスタムパイプ

カスタムパイプは PipeTransform.transform() を実装します。@Pipe の name がテンプレートで使われます。スタンドアロンパイプ(v15+)はコンポーネントの imports 配列に登録するか、NgModule で宣言します。純粋パイプ(デフォルト)は入力の参照が変わったときだけ再実行されるため、更新を引き起こすには新しい参照を渡してください。

angular
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit = 20, ellipsis = '...'): string {
    if (!value) return '';
    return value.length > limit
      ? value.slice(0, limit) + ellipsis
      : value;
  }
}

// register in a standalone component imports:
// imports: [TruncatePipe]

<!-- usage -->
<p>{{ longText | truncate:50 }}</p>
<p>{{ longText | truncate:10:'>>' }}</p>

Async パイプ

async パイプは Observable や Promise を購読して値を描画し、破棄時に自動で購読解除します — 手動の subscribe/unsubscribe が不要です。*ngIf as や @for と組み合わせると、ロード中の null をきれいに処理できます。新しい値が届くとコンポーネントをチェック対象としてマークするため、OnPush とも連携します。

angular
@Component({
  selector: 'app-user',
  template: `
    <div *ngIf="user$ | async as user">
      {{ user.name }}
    </div>
    <ul>
      @for (item of items$ | async; track item.id) {
        <li>{{ item.name }}</li>
      }
    </ul>
  `,
  imports: [AsyncPipe, NgIf],
})
export class UserComponent {
  user$ = this.http.get<User>('/api/user');
  items$ = this.http.get<Item[]>('/api/items');

  constructor(private http: HttpClient) {}
}

純粋パイプと非純粋パイプ

純粋パイプは入力の参照が変わるまで結果をキャッシュするため、配列やオブジェクトをミューテートしても発火しません。非純粋パイプ(pure: false)は毎回の変更検知で再実行されます — ミューテートされる配列のフィルタリングに便利ですがコストが高いです。データを不変に保ち(ミューテートの代わりに配列を差し替え)、純粋パイプを使うのがパフォーマンス上の好例です。

angular
// PURE (default): re-runs only when input reference changes
@Pipe({ name: 'filter' })
export class FilterPipe implements PipeTransform {
  transform(items: Item[], term: string): Item[] {
    return items.filter(i => i.name.includes(term));
  }
}
// Issue: mutating items.push() won't trigger re-evaluation.

// IMPURE: re-runs on every change detection cycle
@Pipe({ name: 'filter', pure: false })
export class ImpureFilterPipe implements PipeTransform { ... }
// ⚠️ Expensive! Use sparingly — affects performance.

i18n とロケールパイプ

date、number、currency などのパイプは LOCALE_ID に従います。ブートストラップ前に registerLocaleData でロケールデータを登録します。currency や数値の書式はアクティブなロケールに従います。多言語アプリではユーザーごとに LOCALE_ID を提供するか、i18n ツールでテンプレート翻訳を行います。ロケールデータが不足すると en-US にフォールバックします。

angular
// register locale data in app.config.ts
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
registerLocaleData(localeFr);

// provide a default locale
providers: [{ provide: LOCALE_ID, useValue: 'fr-FR' }]

// usage - now locale-aware
<p>{{ price | currency:'EUR' }}</p>          <!-- 1 234,56 € -->
<p>{{ today | date:'fullDate' }}</p>          <!-- lundi 10 septembre 2024 -->
<p>{{ number | number:'1.2-2' }}</p>          <!-- 1 234,56 -->
<p>{{ amount | currency:'JPY' }}</p>          <!-- ¥1,235 -->
06

サービスと依存性注入

基本のサービス

providedIn: 'root' を指定するとモジュール登録なしでアプリ全体から使えるシングルトンになります。サービスは tree-shaking 可能で、未使用なら削除されます。コンストラクタ注入の代わりに inject() 関数(v14+)を使うとコードが読みやすくテストもしやすくなります。サービスは共有状態とビジネスロジックを担い、コンポーネントは表示に専念させましょう。

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

@Injectable({ providedIn: 'root' })
export class UserService {
  private users = ['Alice', 'Bob'];

  getUsers() { return this.users; }
  addUser(name: string) { this.users.push(name); }
}

// usage in a component
export class UserListComponent {
  // Angular injects the singleton instance
  constructor(private users: UserService) {}

  get users() { return this.usersService.getUsers(); }
  private usersService = inject(UserService);
}

inject() 関数

inject() はコンストラクタ注入のモダンな代替です。フィールド初期化子で使えるためコードが読みやすくなり、TypeScript の型推論も向上します。構築中に実行する必要があります(後の非同期コールバック内では不可)。一貫して使うのが良いでしょう — コンストラクタ引数と inject() の混在は可能ですが、inject() の方がきれいです。

angular
import { Injectable, inject } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class AuthService {
  private http = inject(HttpClient);
  private router = inject(Router);

  login(creds: Credentials) {
    return this.http.post('/api/login', creds);
  }
}

// in a component
export class DashboardComponent {
  private auth = inject(AuthService);
  user = this.auth.currentUser;   // works in field initializers
}

プロバイダの設定

プロバイダは任意のレベル(root、モジュール、コンポーネント)で設定できます。useClass は実装を差し替えます(モックに最適)。useValue は定数を提供し、useExisting はあるサービスを別のサービスの別名にします。useFactory は動的にインスタンスを生成します。InjectionToken は文字列や設定オブジェクトなどクラス以外の値に使います。

angular
@Component({
  // ... provide at component level for instance-per-component
  providers: [
    UserService,                              // shorthand
    { provide: Logger, useClass: ConsoleLogger },
    { provide: API_URL, useValue: 'https://api.example.com' },
    { provide: Storage, useExisting: LocalStorageService },
    {
      provide: Config,
      useFactory: () => new Config(env.production)
    },
  ],
})
export class AdminComponent {}

// InjectionToken for non-class values
export const API_URL = new InjectionToken<string>('API_URL');

階層的インジェクタ

Angular の DI ツリーはコンポーネントツリーを反映します。providedIn: 'root' ならアプリ全体で 1 インスタンスです。コンポーネントレベルのプロバイダは子インジェクタを作り、各インスタンスが独自のコピーを受け取ります。エディタのような状態を持つコンポーネントに有用です。'any' は遅延モジュールにスコープし、'platform' はマルチアプリ構成用のまれな設定です。

angular
// root injector (singleton app-wide)
@Injectable({ providedIn: 'root' })
export class AuthService {}

// component-level provider: new instance for this component and children
@Component({
  providers: [UserService],   // each AdminComponent gets its own UserService
})
export class AdminComponent {}

// 'any' creates a lazy singleton per lazy module
@Injectable({ providedIn: 'any' })
export class SharedService {}

// 'platform' shared across all Angular apps on the page
@Injectable({ providedIn: 'platform' })
export class GlobalConfig {}

マルチプロバイダとトークン

multi: true を指定すると 1 つのトークンに複数のプロバイダを登録でき、配列として注入されます。プラグインシステム、インターセプター、バリデーターなど拡張可能なコレクションに有用です。注入順序は登録順に従います。InjectionToken と組み合わせれば配列に適切な型を付けられます。

angular
// define a token for a list of plugins
export const PLUGIN = new InjectionToken<Plugin>('PLUGIN');

// provide multiple plugins
@Component({
  providers: [
    { provide: PLUGIN, useClass: AuthPlugin, multi: true },
    { provide: PLUGIN, useClass: AnalyticsPlugin, multi: true },
  ],
})
export class AppComponent {}

// inject all of them as an array
export class PluginManager {
  plugins = inject(PLUGIN);   // Plugin[]
}

オプショナル・デフォルトプロバイダ

@Optional() や inject(token, { optional: true }) はプロバイダが見つからない場合に例外の代わりに null を返します。必須でない依存関係に使いましょう。他の修飾子:@SkipSelf()(現在のインジェクタを検査しない)、@Self()(現在のみ)、@Host()(ホストコンポーネントまで)。inject() でもオプションオブジェクトでフラグを指定できます。

angular
import { Injectable, inject, Optional, Inject } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class Logger {
  constructor(@Optional() @Inject(CONFIG) private cfg?: Config) {
    // cfg is null if no provider exists — handle gracefully
  }
}

// or with inject()
export class Service {
  cfg = inject(CONFIG, { optional: true });   // Config | null
  baseUrl = inject(API_URL, { optional: true }) ?? '/api';
}

// skipSelf: look in parent injectors only
// self: only this component's injector
// host: limit to host component
07

ルーティング

ルート設定

ルートは URL パスをコンポーネントにマッピングします。loadComponent/loadChildren で遅延ロードが有効になり初期バンドルが小さくなります。:id はルートパラメータです。ワイルドカード '**' は未一致の URL を受け止めます — 最後に置いてください。provideRouter がスタンドアロンアプリにルーターをセットアップします。title を設定するとブラウザタブ名になります(文字列または ResolveFn)。

angular
// app.routes.ts (standalone)
import { Routes } from '@angular/router';

export const routes: Routes = [
  { path: '', component: HomeComponent, title: 'Home' },
  { path: 'about', loadComponent: () => import('./about/about.component')
      .then(m => m.AboutComponent) },
  { path: 'users/:id', component: UserDetailComponent },
  { path: 'admin', loadChildren: () => import('./admin/admin.routes')
      .then(m => m.ADMIN_ROUTES) },
  { path: '**', component: NotFoundComponent },   // wildcard
];

// app.config.ts
export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes)]
};

Router Outlet とリンク

router-outlet はルーティングされたコンポーネントの描画位置を示します。routerLink でナビゲーションリンクを作り(パラメータは配列形式で)、routerLinkActive はルートが一致したときにクラスを適用します。プログラム的ナビゲーションには router.navigate() または routerLink を使います。名前付き outlet でセカンダリルート(メインビュー横のモーダルなど)が可能です。

angular
<!-- app.component.html -->
<nav>
  <a routerLink="/" routerLinkActive="active">Home</a>
  <a routerLink="/about" routerLinkActive="active">About</a>
  <a [routerLink]="['/users', userId]">My Profile</a>
</nav>

<router-outlet></router-outlet>

<!-- named outlet (secondary route) -->
<router-outlet name="popup"></router-outlet>

<!-- navigate programmatically -->
<button (click)="go()">Go</button>
// constructor(private router: Router) {}
// go() { this.router.navigate(['/users', 42]); }

ルートパラメータとクエリパラメータ

ナビゲーションごとにコンポーネントが破棄・再生成されるなら、一度きりの読み取りには snapshot を使います。同じコンポーネントインスタンスが異なるパラメータを処理する場合(/users/1 から /users/2 への遷移など)は、observable の paramMap/queryParamMap を使います。リークを避けるため必ず購読解除するか async パイプを使いましょう。

angular
// reading route params
export class UserDetailComponent {
  constructor(private route: ActivatedRoute) {
    // snapshot: one-time read (good for static links)
    const id = this.route.snapshot.paramMap.get('id');

    // observable: reacts to param changes (same component reused)
    this.route.paramMap.subscribe(params => {
      console.log(params.get('id'));
    });
  }
}

// query params: /search?q=angular&page=2
this.route.queryParamMap.subscribe(qp => {
  this.q = qp.get('q');
});

<!-- link with query params -->
<a [routerLink]="['/search']" [queryParams]="{ q: 'angular', page: 2 }">

子ルートとネストしたルート

子ルートは親コンポーネント内のネストした router-outlet に描画されます。redirectTo に pathMatch: 'full' を組み合わせると空の子パスをリダイレクトできます。このパターンでマスター詳細レイアウト(親の枠組み + 子のコンテンツ)を構築します。ネストの各レベルには親のテンプレートに独自の router-outlet が必要です。

angular
export const routes: Routes = [
  {
    path: 'admin',
    component: AdminLayoutComponent,
    children: [
      { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
      { path: 'dashboard', component: DashboardComponent },
      { path: 'users', component: AdminUsersComponent },
      { path: 'settings', component: SettingsComponent },
    ],
  },
];

<!-- AdminLayoutComponent template -->
<h2>Admin Panel</h2>
<nav>...</nav>
<router-outlet></router-outlet>   <!-- child routes render here -->

遅延ロード

遅延ロードはアプリを必要時に読み込むチャンクに分割し、初期バンドルを縮小します。loadChildren はルートファイル(Routes のデフォルトエクスポート)をロードし、loadComponent は単一のスタンドアロンコンポーネントをロードします。動的 import() の文字列は、バンドラが正しく分割できるよう静的パスである必要があります。ナビゲーション配下の機能領域に使いましょう。

angular
// main routes - load feature modules on demand
export const routes: Routes = [
  { path: '', component: HomeComponent },
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
  },
  {
    path: 'reports',
    loadComponent: () => import('./reports/reports.component')
      .then(m => m.ReportsComponent),
  },
];

// admin.routes.ts
export const ADMIN_ROUTES: Routes = [
  { path: '', component: AdminComponent },
  { path: 'users', component: AdminUsersComponent },
];

ルーターイベントとナビゲーション

ルーターイベント(NavigationStart、NavigationEnd、GuardsCheckStart など)でナビゲーションライフサイクルを追跡できます。必ず特定のイベントにフィルタし、購読を解除しましょう。router.navigate は extras で queryParams、fragment、state(URL に出ない一時データ)、replaceUrl を受け付けます。state は router.getCurrentNavigation().extras.state で読めます。

angular
// subscribe to router events
export class AppComponent implements OnDestroy {
  private sub = this.router.events.pipe(
    filter((e): e is NavigationEnd => e instanceof NavigationEnd)
  ).subscribe(e => {
    console.log('Navigated to:', e.url);
    this.analytics.track(e.url);
  });

  constructor(private router: Router) {}
  ngOnDestroy() { this.sub.unsubscribe(); }
}

// navigation with extras
this.router.navigate(['/users'], {
  queryParams: { sort: 'name' },
  fragment: 'top',
  state: { from: 'login' },   // passed to next route, not in URL
});
08

フォーム

テンプレート駆動フォーム

テンプレート駆動フォームは ngModel とテンプレート参照を使います。FormsModule が必要です。フォームの状態(有効性、touched、dirty)は ngForm と ngModel ディレクティブで追跡されます。単純なフォームに最適です。バリデーションはテンプレートで宣言し(required、minlength、pattern)、#e='ngModel' のようなテンプレート参照で制御状態にアクセスします。

angular
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [FormsModule],
  template: `
    <form #f="ngForm" (ngSubmit)="save(f.value)">
      <input name="email" [(ngModel)]="email" required email #e="ngModel" />
      <span *ngIf="e.invalid && e.touched">Email required</span>

      <input name="pwd" type="password" [(ngModel)]="pwd" required minlength="6" />
      <button [disabled]="f.invalid">Submit</button>
    </form>
  `,
})
export class LoginComponent {
  email = '';
  pwd = '';
  save(v: any) { console.log(v); }
}

リアクティブフォームのセットアップ

リアクティブフォームはコンポーネントクラス内で FormControl/FormGroup インスタンスとしてモデルを定義します。ReactiveFormsModule が必要です。formControlName で入力をコントロールに束縛します。フォームモデルは observable であり、DOM なしでテスト可能です。nonNullable: true にすると入力が空になったときに null になりません。複雑なフォームに推奨されます。

angular
import { ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-profile',
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="save()">
      <input formControlName="name" />
      <input formControlName="email" />
      <button [disabled]="form.invalid">Save</button>
    </form>
    <p>Valid: {{ form.valid }}</p>
  `,
})
export class ProfileComponent {
  form = new FormGroup({
    name: new FormControl('', { nonNullable: true }),
    email: new FormControl('', { nonNullable: true }),
  });
  save() { console.log(this.form.value); }
}

FormBuilder と型付きフォーム

FormBuilder はボイラープレートを減らします。fb.group() はデフォルト値から型を推論します。ネストしたグループでネストしたデータをモデル化し、FormArray で動的なコントロールのリストを管理します。nonNullable を使うとコントロールは宣言型のままになり null になりません。get() や controls で型安全にアクセスできます。型付きフォーム(v14+)は value の自動補完と型チェックを提供します。

angular
import { FormBuilder, FormGroup } from '@angular/forms';

export class CheckoutComponent {
  private fb = inject(FormBuilder);

  // typed form (v14+ nonNullable)
  form = this.fb.group({
    name: ['', { nonNullable: true }],
    address: this.fb.group({
      street: [''],
      city: [''],
      zip: [''],
    }),
    items: this.fb.array<CartItem>([]),
  });

  // type-safe access
  get items() { return this.form.controls.items; }
  addItem(item: CartItem) { this.items.push(this.fb.control(item)); }
}

フォームバリデーション

Validators.required、.minLength、.maxLength、.pattern、.email、.min、.max が組み込みです。配列で複数適用できます。クロスフィールドバリデーションは FormGroup 上に、グループ全体を受け取るバリデーター関数として置きます。初回描画でユーザーを責めないよう、エラー表示の前に control.touched/dirty を確認しましょう。特定のエラーの判定には .hasError('key') を使います。

angular
import { Validators } from '@angular/forms';

// built-in validators
const email = new FormControl('', [
  Validators.required,
  Validators.email,
  Validators.maxLength(100),
]);

const password = new FormControl('', [
  Validators.required,
  Validators.minLength(8),
  Validators.pattern(/[A-Z]/),
]);

// cross-field validation at group level
const form = this.fb.group({
  pwd: ['', Validators.required],
  confirm: ['', Validators.required],
}, { validators: matchPassword });   // custom group validator

// reading state in template
<!-- <span *ngIf="email.touched && email.hasError('required')">Required</span> -->

カスタムバリデーター

カスタムバリデーターは ValidationErrors(マップ)または有効なら null を返す関数です。非同期バリデーターは Observable か Promise を返し、ユーザー名の利用可否チェックのようなサーバー側検証に使います。すべてのキー入力でサーバーを叩かないよう、非同期バリデーターは必ず debounce(timer/switchMap など)しましょう。

angular
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

// function validator
export const matchPassword: ValidatorFn = (group: AbstractControl): ValidationErrors | null => {
  const pwd = group.get('pwd')?.value;
  const confirm = group.get('confirm')?.value;
  return pwd === confirm ? null : { mismatch: true };
};

// async validator (returns Observable/Promise)
export function uniqueUsername(http: HttpClient): AsyncValidatorFn {
  return (control: AbstractControl) => {
    return timer(500).pipe(
      switchMap(() => http.get(`/api/check/${control.value}`)),
      map(exists => exists ? { taken: true } : null),
    );
  };
}

フォームの値変更と状態

valueChanges と statusChanges は入力のたびに発火する Observable です。debounceTime で高速なタイピングによる過剰な処理を防ぎます。破棄時の購読解除には Subject と takeUntil の組み合わせが定石です。patchValue は部分的な値を更新し、setValue は全フィールドを要求します。{ emitEvent: false } を使うと valueChanges を発火させずにサイレント更新できます。

angular
export class FilterComponent implements OnDestroy {
  private destroy = new Subject<void>();
  form = this.fb.group({ q: [''], category: ['all'] });

  ngOnInit() {
    // react to entire form changes (debounced)
    this.form.valueChanges.pipe(
      debounceTime(300),
      takeUntil(this.destroy),
    ).subscribe(v => this.search(v));

    // react to a single control
    this.form.controls.q.valueChanges.subscribe(q => {
      console.log('q changed:', q);
    });
  }

  ngOnDestroy() { this.destroy.next(); }
}
09

HttpClient

セットアップと基本の GET

provideHttpClient() がアプリ全体にクライアントを登録します。HttpClient のメソッドはコールドな Observable を返すため、購読したときにだけ実行されます(テンプレートでは async パイプ、サービス内では subscribe)。レスポンスはジェネリクスで型付けします。エラーは一元管理するか呼び出しごとに処理しましょう。withFetch()(v18)でモダンな fetch バックエンドを選択できます。

angular
// app.config.ts
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [provideHttpClient()],
};

// usage in a service
@Injectable({ providedIn: 'root' })
export class PostService {
  private http = inject(HttpClient);
  private api = 'https://jsonplaceholder.typicode.com/posts';

  getPosts() {
    return this.http.get<Post[]>(this.api);
  }
}

// in a component (use async pipe to auto-unsubscribe)
export class PostListComponent {
  posts$ = this.posts.getPosts();
  constructor(private posts: PostService) {}
}

POST / PUT / DELETE

post/put/patch はレスポンスを 1 回だけ出力して完了する Observable を返します。ボディは第 2 引数で渡します。ジェネリック型でレスポンスを絞り込めます。URL はパラメータを埋め込んだテンプレートリテラルにできます。Observable はコールドなので、必ず subscribe しないと動きません。1 回限りの読み取りには toPromise()(非推奨)か firstValueFrom() を検討しましょう。

angular
export class PostService {
  private http = inject(HttpClient);

  create(post: Omit<Post, 'id'>) {
    return this.http.post<Post>('/api/posts', post);
  }

  update(id: number, patch: Partial<Post>) {
    return this.http.put<Post>(`/api/posts/${id}`, patch);
  }

  remove(id: number) {
    return this.http.delete<void>(`/api/posts/${id}`);
  }
}

// all return Observables — subscribe or use async pipe
// HTTP methods return a single value then complete

クエリパラメータとヘッダー

params にはオブジェクト、HttpParams、配列を渡せます — Angular がクエリ文字列にエンコードします。headers でリクエストヘッダーを設定します。observe: 'response' を指定するとボディだけでなく完全な HttpResponse(ステータス、ヘッダー、ボディ)を取得できます。observe: 'events' と reportProgress の組み合わせで、ファイルのアップロード/ダウンロードの進捗イベントをストリームできます。

angular
export class SearchService {
  private http = inject(HttpClient);

  search(term: string, page = 1) {
    return this.http.get<Result[]>('/api/search', {
      params: { q: term, page, sort: 'desc' },
      headers: { 'X-Api-Key': 'secret' },
      observe: 'response',   // get full HttpResponse
      responseType: 'json',
    });
  }

  // observe: 'events' streams upload/download progress
  upload(file: File) {
    return this.http.post('/api/upload', file, {
      reportProgress: true,
      observe: 'events',
    });
  }
}

インターセプター

関数型インターセプター(v15+)は withInterceptors() で連結する普通の関数です。すべてのリクエストに対して順に実行され、認証トークン、ロギング、リトライ、キャッシュに最適です。clone() で修正済みのリクエストを作れます(リクエストは不変)。next(req) がレスポンスストリームを返すので、retry や catchError などのパイプ演算子をここに適用します。

angular
// functional interceptor (v15+)
export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = localStorage.getItem('token');
  const authReq = token
    ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })
    : req;
  return next(authReq);
};

// register in app.config.ts
providers: [provideHttpClient(withInterceptors([authInterceptor]))]

// error/logging interceptor
export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
  console.log('Request:', req.url);
  return next(req).pipe(tap({
    error: e => console.error('Failed:', req.url, e),
  }));
};

エラーハンドリング

HTTP の耐障害性には RxJS 演算子を使います:retry はエラー時に再購読し、timeout は遅いリクエストを打ち切り、catchError はエラーをフォールバック値へ変換するか再スローします。利用者側でもエラーを処理しましょう — 捕捉されない Observable エラーはストリームを止めます。next/error/complete コールバック付きで購読すればライフサイクル全体を扱えます。

angular
export class PostService {
  getPost(id: number) {
    return this.http.get<Post>(`/api/posts/${id}`).pipe(
      retry(2),                              // retry on failure
      timeout(5000),                         // abort after 5s
      catchError(err => {
        if (err.status === 404) return of(null);   // graceful fallback
        return throwError(() => new Error('Network error'));
      }),
    );
  }
}

// component-side
this.posts.getPost(1).subscribe({
  next: p => this.post = p,
  error: e => this.error = e.message,
  complete: () => this.loading = false,
});

型付きレスポンスと withFetch

ジェネリクスはレスポンスボディの型を付けますが実行時検証はしません — 安全には zod のようなランタイムバリデーターを使いましょう。observe: 'response' でステータス、ヘッダー、ボディにアクセスできます。withFetch()(v18)は XHR の代わりに Fetch API を使い、ストリーミングとより良いサーバーサイドレンダリングを可能にします。withXsrfConfiguration で CSRF トークンを自動処理できます。

angular
// typed generic — response is typed, runtime NOT validated
this.http.get<User[]>('/api/users');

// full HttpResponse observation
this.http.get<User>('/api/users/1', { observe: 'response' })
  .subscribe(res => {
    console.log(res.status);   // 200
    console.log(res.headers.get('X-Total-Count'));
    console.log(res.body);     // User
  });

// opt into fetch() backend (v18+, recommended)
// provideHttpClient(withFetch())

// with XSRF protection enabled
// provideHttpClient(withXsrfConfiguration({ cookieName: 'XSRF-TOKEN' }))
10

Observable と RxJS

基本の Observable

Observable は遅延評価です — 購読されるまでプロデューサーは動きません。0 個以上の値を出力した後、complete または error で終わります。subscribe のコールバックは next、error、complete を受け取ります。長期間生きる購読は必ず解除しましょう(async パイプや takeUntilDestroyed を使う)。of() は同期的に値を出力し、from() は配列や Promise を平坦化します。

angular
import { Observable } from 'rxjs';

const obs = new Observable<number>(subscriber => {
  subscriber.next(1);
  subscriber.next(2);
  setTimeout(() => {
    subscriber.next(3);
    subscriber.complete();
  }, 1000);
});

const sub = obs.subscribe({
  next: v => console.log(v),
  error: e => console.error(e),
  complete: () => console.log('done'),
});

// cleanup
sub.unsubscribe();

// use of(...) for synchronous values
of(1, 2, 3).subscribe(v => console.log(v));
// from(iterable) for arrays/async iterables
from([1, 2, 3]).subscribe(console.log);

よく使う演算子

演算子はストリームを変換します。map/filter は配列メソッドと同じ感覚で使えます。debounceTime は静まるまで待つ(検索入力に最適)。distinctUntilChanged は連続した重複値をスキップします。switchMap は新しい値が来たとき前の内部 Observable をキャンセルするので、入力しながら検索に最適です。パイプ演算子は左から右へ評価されます。

angular
import { of, from, interval } from 'rxjs';
import { map, filter, switchMap, debounceTime, distinctUntilChanged } from 'rxjs/operators';

of(1, 2, 3, 4).pipe(
  map(x => x * 10),                          // 10, 20, 30, 40
  filter(x => x > 15),                       // 20, 30, 40
).subscribe(console.log);

// search input with debounce
input$.pipe(
  debounceTime(300),
  distinctUntilChanged(),
  switchMap(term => http.get(`/api/search?q=${term}`)),
).subscribe(results => this.results = results);

ストリームの結合

combineLatest は(全ソースが少なくとも 1 回出力した後)どれかが発火するたびに出力します — 派生的なビュー状態に最適。forkJoin は全ソースの完了を待ち、それぞれの最後の値を返すので、並列 HTTP リクエストに使います。merge は出力を交互に流し、zip はインデックスでペアにし、race は最初に発火した Observable を選び残りを無視します。

angular
import { combineLatest, forkJoin, merge, race, zip } from 'rxjs';

// combineLatest: emits when ANY source emits, after all have emitted
combineLatest([user$, settings$]).subscribe(([u, s]) => ...);

// forkJoin: waits for all to complete, emits last values (like Promise.all)
forkJoin({ user: user$, posts: posts$ }).subscribe(r => ...);

// merge: emits values from all sources as they come
merge(clicks$, keys$).subscribe(e => ...);

// zip: pairs emissions by index
zip(range(1, 3), ['a', 'b', 'c']).subscribe(([n, letter]) => ...);

// race: takes the first to emit, ignores the rest
race(primary$, fallback$).subscribe(v => ...);

Subject(マルチキャスト)

Subject は Observable であり Observer でもあります — .next() で値を push します。Subject は初期値がなく、後から来た購読者は過去の出力を受け取りません。BehaviorSubject は初期値が必須で、新しい購読者はすぐ現在値を受け取ります(状態に使用)。ReplaySubject は最後の N 個をバッファし新規購読者へ再送します(イベントの再生に使用)。

angular
import { Subject, BehaviorSubject, ReplaySubject } from 'rxjs';

// Subject: emits to current subscribers only
const click$ = new Subject<MouseEvent>();
click$.subscribe(x => console.log('A:', x));
click$.next({} as MouseEvent);   // A: logs it

// BehaviorSubject: keeps last value, new subs get it immediately
const count$ = new BehaviorSubject(0);
count$.subscribe(v => console.log(v));   // logs 0 immediately
count$.next(1);                          // logs 1 to subscribers

// ReplaySubject: replays last N values to new subscribers
const recent$ = new ReplaySubject<string>(2);
recent$.next('a'); recent$.next('b'); recent$.next('c');
recent$.subscribe(v => console.log(v));  // logs 'b', then 'c'

takeUntil と後始末

takeUntil(unsubscribe$) はノーティファイアが発火したら購読を自動完了させます — コンポーネントでのリーク防止の標準パターンです。takeUntilDestroyed()(v16+)は Angular の DestroyRef を使って OnDestroy のボイラープレートなしで自動購読解除します。注入コンテキスト(コンストラクタやフィールド初期化子)で呼ぶか、DestroyRef を明示的に渡す必要があります。

angular
import { Subject, takeUntil, takeUntilDestroyed } from 'rxjs';

export class DemoComponent implements OnDestroy {
  private destroy$ = new Subject<void>();

  ngOnInit() {
    this.svc.stream$.pipe(
      takeUntil(this.destroy$),
    ).subscribe(data => this.data = data);
  }

  ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); }
}

// v16+: takeUntilDestroyed (uses DestroyRef, no boilerplate)
export class DemoComponent {
  data: any;
  constructor() {
    inject(SomeService).stream$.pipe(
      takeUntilDestroyed(),
    ).subscribe(d => this.data = d);
  }
}

switchMap / mergeMap / concatMap の違い

これらの平坦化演算子は、内部 Observable が重なったときの扱いが違います。switchMap はキャンセル(入力しながら検索)、mergeMap は並列(多数ロード)、concatMap は順番待ち(順序維持)、exhaustMap は無視(二重送信防止)。選択を誤ると競合状態が起きます — ユースケースのキャンセル性に合わせて演算子を選びましょう。

angular
import { from, interval } from 'rxjs';
import { switchMap, mergeMap, concatMap, exhaustMap } from 'rxjs/operators';

// switchMap: cancels the previous inner stream on new value
input$.pipe(switchMap(term => search(term)));
// Best for: typeahead search (discard stale results)

// mergeMap: runs all inner streams in parallel
ids$.pipe(mergeMap(id => fetchDetail(id)));
// Best for: parallel requests, order doesn't matter

// concatMap: queues inner streams, runs one at a time
queue$.pipe(concatMap(task => runTask(task)));
// Best for: ordered sequential operations

// exhaustMap: ignores new values while inner stream is active
save$.pipe(exhaustMap(() => saveForm()));
// Best for: prevent double-submit (ignore clicks while saving)
11

ライフサイクルフック

フックの順序

フックは厳密な順序で発火します。ngOnChanges は @Input の変更時に(初期化時も)発火し、ngOnInit は最初の ngOnChanges の後に 1 回だけ発火します。ngDoCheck は毎回の変更検知サイクルで動きます。After* 系フックはコンテンツ/ビューが DOM クエリ可能になった合図です。ngOnDestroy は後始末の場所です — 購読解除、リソース解放、タイマー停止を行いましょう。

angular
export class LifecycleComponent implements
    OnChanges, OnInit, DoCheck, AfterContentInit,
    AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {

  ngOnChanges()    { console.log('1. input changes'); }
  ngOnInit()       { console.log('2. component init (once)'); }
  ngDoCheck()      { console.log('3. custom change detection'); }
  ngAfterContentInit()      { console.log('4. projected content ready'); }
  ngAfterContentChecked()   { console.log('5. projected content checked'); }
  ngAfterViewInit()         { console.log('6. view (template) ready'); }
  ngAfterViewChecked()      { console.log('7. view checked'); }
  ngOnDestroy()    { console.log('8. cleanup before destroy'); }
}

ngOnInit と ngOnDestroy

ngOnInit は入力が設定された後に 1 回動くため、重い初期化(データ取得、購読)に適した場所です — コンストラクタは軽く保つべきです。ngOnDestroy はコンポーネント破棄時に呼ばれる唯一のフックで、ここで後始末を省略すると購読・タイマー・イベントリスナーがリークします。コンストラクタは DI 専用にし、ロジックは ngOnInit に書きましょう。

angular
export class ChartComponent implements OnInit, OnDestroy {
  private timer?: ReturnType<typeof setInterval>;

  ngOnInit() {
    // good for: data fetching, initialization, subscriptions
    this.timer = setInterval(() => this.refresh(), 5000);
    this.loadInitialData();
  }

  ngOnDestroy() {
    // cleanup: clear timers, unsubscribe, release resources
    if (this.timer) clearInterval(this.timer);
    // also: this.sub.unsubscribe();
  }

  private refresh() { /* ... */ }
  private loadInitialData() { /* ... */ }
}

ngOnChanges(SimpleChange)

ngOnChanges は @Input の参照が変わるたびに発火し、SimpleChanges マップを受け取ります:各エントリには previousValue、currentValue、firstChange、isFirstChange() があります。オブジェクトのプロパティをミューテートしたときには発火しません — 参照が変わったときだけです。深い変更には setter 付き @Input や ngDoCheck + IterableDiffers を使いましょう。

angular
export class PaginationComponent implements OnChanges {
  @Input() page = 1;
  @Input() total = 0;

  ngOnChanges(changes: SimpleChanges) {
    if (changes['page'] && !changes['page'].firstChange) {
      // react only when page actually changed (not on init)
      console.log('page:', changes['page'].previousValue, '->', changes['page'].currentValue);
      this.fetchPage(this.page);
    }
  }

  private fetchPage(p: number) { /* ... */ }
}

ngAfterViewInit と ViewChild

ViewChild/ContentChild のクエリは対応する init フックの後に解決されます。ngAfterViewInit はコンポーネント自身のテンプレートの要素向け、ngAfterContentInit は <ng-content> で投影されたコンテンツ向けです。ngOnInit でこれらの参照にアクセスすると undefined になります。! 非NULLアサーションは初期化後に設定されるとコンパイラに伝えるもので、After* フックでのみ安全に使えます。

angular
export class CanvasComponent implements AfterViewInit {
  @ViewChild('canvas') canvasRef!: ElementRef<HTMLCanvasElement>;

  // ❌ canvasRef is undefined in ngOnInit
  ngOnInit() { /* this.canvasRef is undefined here */ }

  // ✅ available after view init
  ngAfterViewInit() {
    const canvas = this.canvasRef.nativeElement;
    const ctx = canvas.getContext('2d');
    ctx?.fillText('Hello', 10, 50);
  }
}

// template: <canvas #canvas></canvas>

ngDoCheck(カスタム検知)

ngDoCheck は毎回の変更検知サイクルで動くため軽量に保ちましょう。IterableDiffers/KeyValueDiffers を使うと、参照が変わらないために ngOnChanges が検知できない配列/オブジェクトのミューテーションを検出できます。内部のミューテーションを追跡するための逃げ道です。頻繁に実行されるため重いロジックは避けましょう — パフォーマンス問題の原因になります。

angular
export class ListComponent implements DoCheck {
  @Input() items: Item[] = [];
  private differ: IterableDiffer<Item>;

  constructor(differs: IterableDiffers) {
    this.differ = differs.find(items).create<Item>((i) => i.id);
  }

  ngDoCheck() {
    const changes = this.differ.diff(this.items);
    if (changes) {
      changes.forEachAddedItem(r => console.log('Added:', r.item));
      changes.forEachRemovedItem(r => console.log('Removed:', r.item));
    }
  }
}

コンテンツフックとビューフック

コンテンツフック(AfterContentInit/Checked)は <ng-content> で投影されたコンテンツに対して発火します。ビューフック(AfterViewInit/Checked)はコンポーネント自身のテンプレートに対して発火します。ビューが完成する前にコンテンツが初期化されるため、コンテンツフックが先に発火します。投影された要素は @ContentChild、自テンプレートの要素は @ViewChild でクエリします。

angular
export class CardComponent implements
    AfterContentInit, AfterViewInit, AfterContentChecked, AfterViewChecked {

  @ContentChild('header') headerTpl?: TemplateRef<unknown>;
  @ViewChild('body') bodyEl?: ElementRef<HTMLElement>;

  // projected content (<ng-content>) is ready
  ngAfterContentInit() {
    console.log('content ready:', this.headerTpl);
  }

  // own template view is ready
  ngAfterViewInit() {
    console.log('view ready:', this.bodyEl?.nativeElement);
  }

  // ContentChecked/ViewChecked run every CD cycle after init — beware perf
}
12

コンテンツ投影

基本の ng-content

<ng-content> は親が渡したコンテンツが投影されるプレースホルダーです。Angular 版の <slot> と考えましょう。select がなければすべての投影コンテンツがここに入ります。投影コンテンツは親のコンテキストでコンパイルされるため、{{ }} のようなバインディングは CardComponent ではなく親コンポーネントで解決されます。

angular
// card.component.ts
@Component({
  selector: 'app-card',
  template: `
    <div class="card">
      <ng-content></ng-content>
    </div>
  `,
  styles: ['.card { border: 1px solid #ccc; padding: 16px; }'],
})
export class CardComponent {}

<!-- usage: anything inside projects into <ng-content> -->
<app-card>
  <h3>Title</h3>
  <p>Body content here.</p>
</app-card>

マルチスロット投影

ng-content の select 属性で特定の投影コンテンツをターゲットにできます:要素('header')、属性('[header]')、クラス('.active')、その組み合わせ('div.foo[bar]')。どのセレクタにも一致しなかったコンテンツは select のない ng-content に入ります。投影コンテンツは親のスタイルとコンテキストを保ち、DOM 上の位置だけが変わります。

angular
@Component({
  selector: 'app-layout',
  template: `
    <header><ng-content select="[header]"></ng-content></header>
    <main><ng-content></ng-content></main>
    <footer><ng-content select="footer"></ng-content></footer>
  `,
})
export class LayoutComponent {}

<!-- usage: select matches attributes, elements, classes -->
<app-layout>
  <nav header>Top nav</nav>
  <p>Main body</p>
  <footer>Bottom</footer>
</app-layout>

条件付き投影(ng-template)

条件付きや繰り返しの投影には ng-template と ngTemplateOutlet で完全に制御できます。ContentChildren で投影されたディレクティブをクエリします。ngTemplateOutlet は TemplateRef を任意の場所に描画できるので、タブ、アコーディオン、条件付きスロットに有用です。このパターンでコンテンツの宣言と描画場所・タイミングを分離できます。

angular
@Component({
  selector: 'app-tabs',
  template: `
    <div class="tabs">
      @for (t of tabs; track t) {
        <button (click)="active = t">{{ t.title }}</button>
      }
    </div>
    @for (t of tabs; track t) {
      @if (t === active) {
        <ng-container [ngTemplateOutlet]="t.template" />
      }
    }
  `,
})
export class TabsComponent {
  @ContentChildren(TabDirective) tabs!: QueryList<TabDirective>;
  active: any;
}

ContentChild と ContentChildren

@ContentChild / @ContentChildren は投影されたコンテンツをクエリします(自テンプレートは ViewChild)。ContentChildren は QueryList を返し、コンテンツが変わると更新されます。ngAfterContentInit で解決します。{ descendants: true } オプション(デフォルト)はすべての投影コンテンツを走査します。{ read: ... } で特定の型(ElementRef、TemplateRef など)を取得できます。

angular
@Directive({ selector: 'tab' })
export class TabDirective {
  @Input() title = '';
  @Input() active = false;
  @ContentChild(TemplateRef) template!: TemplateRef<unknown>;
}

@Component({
  selector: 'app-tabset',
  template: `
    @for (tab of tabs; track tab) {
      <button (click)="select(tab)">{{ tab.title }}</button>
    }
    <ng-container *ngTemplateOutlet="activeTab?.template" />
  `,
})
export class TabsetComponent implements AfterContentInit {
  @ContentChildren(TabDirective) tabs!: QueryList<TabDirective>;
  activeTab?: TabDirective;

  ngAfterContentInit() {
    this.activeTab = this.tabs.find(t => t.active) ?? this.tabs.first;
  }
}

コンテキスト付き ngTemplateOutlet

ngTemplateOutlet は TemplateRef をオプションのコンテキスト付きで描画します。let-x は context.$implicit(デフォルト値)に、let-y='key' は context.key に束縛されます。*ngFor や ngTemplateOutlet がループ変数を渡す仕組みです。親がカスタマイズでき、反復ロジックはコンポーネントが制御する、再利用可能なリスト/グリッド/アイテムテンプレートに使えます。

angular
@Component({
  selector: 'app-list',
  template: `
    @for (item of items; track item.id) {
      <ng-container *ngTemplateOutlet="itemTpl; context: { $implicit: item, i: $index }" />
    }
    <ng-template #itemTpl let-item let-i="i">
      <li>{{ i }}: {{ item.name }}</li>
    </ng-template>
  `,
})
export class ListComponent {
  items = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];
}

ng-content select のパターン

select は CSS 風のセレクタを受け付けます:クラス(.x)、属性([x])、要素(header)、カンマ区切りのリスト('a, b')。どのセレクタにも一致しないコンテンツは select のない ng-content に入ります。フォールバックが存在しない場合、一致しないコンテンツは破棄されます。セレクタは投影される要素自身の属性にマッチし、内部構造にはマッチしません。

angular
@Component({
  selector: 'app-modal',
  template: `
    <div class="modal">
      <ng-content select=".modal-header"></ng-content>
      <ng-content select="[body]"></ng-content>
      <ng-content select="app-modal-footer, footer"></ng-content>
      <!-- fallback for unmatched content -->
      <ng-content></ng-content>
    </div>
  `,
})

<!-- matches by class, attribute, element, or selector list -->
<app-modal>
  <div class="modal-header">Title</div>
  <section body>Body text</section>
  <app-modal-footer>OK</app-modal-footer>
  <p>This falls into the unselect'd slot.</p>
</app-modal>
13

ルートガード

CanActivate(関数型)

関数型ガード(v14.2+)は true/false/UrlTree、またはそれらの Observable/Promise を返します。UrlTree を返すとそのルートへリダイレクトします。ガードは注入コンテキストで実行されるため inject() が使えます。CanActivate はルートへのナビゲーションを阻止します。ルートごとに canActivate 配列へ登録し、そのルートへのナビゲーションのたびに実行されます。

angular
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';

export const authGuard: CanActivateFn = (route, state) => {
  const auth = inject(AuthService);
  const router = inject(Router);

  if (auth.isLoggedIn) return true;

  // redirect to login, preserving the attempted URL
  return router.createUrlTree(['/login'], {
    queryParams: { returnUrl: state.url },
  });
};

// register in routes
{ path: 'dashboard', component: DashboardComponent, canActivate: [authGuard] }

CanActivateChild

CanActivateChild は親配下の各子ルートの前に実行されます — すべての子に canActivate を繰り返すよりきれいです。機能領域の共通保護に使いましょう。戻り値の型は CanActivate と同じです。親自身も保護するには、親ルートにも canActivate を追加します。

angular
export const adminGuard: CanActivateChildFn = (route, state) => {
  const auth = inject(AuthService);

  if (!auth.isAdmin) {
    return inject(Router).parseUrl('/forbidden');
  }
  return true;
};

// applies to all children of this route
{
  path: 'admin',
  canActivateChild: [adminGuard],
  children: [
    { path: 'users', component: AdminUsersComponent },
    { path: 'settings', component: AdminSettingsComponent },
  ],
}

CanDeactivate(未保存変更のガード)

CanDeactivate はルートを離れる前に実行されるため、未保存のフォーム変更の警告に最適です。ガードはコンポーネントインスタンスを受け取るので、そのメソッドを呼び出せます。false を返すとナビゲーションがキャンセルされ、true で続行します。非同期(モーダル確認)の場合は Observable や Promise を返します。コンポーネント側はガードが期待する契約を実装する必要があります。

angular
import { CanDeactivateFn } from '@angular/router';
import { inject } from '@angular/core';

export interface CanComponentDeactivate {
  canDeactivate: () => boolean | Observable<boolean>;
}

export const unsavedGuard: CanDeactivateFn<CanComponentDeactivate> = (component) => {
  return component?.canDeactivate() ?? true;
};

// component
export class EditComponent implements CanComponentDeactivate {
  canDeactivate() {
    if (this.form.dirty) return confirm('Discard changes?');
    return true;
  }
}

// route: { path: 'edit/:id', canDeactivate: [unsavedGuard] }

CanMatch(条件付きロード)

CanMatch(v14.1+)は遅延ルートのチャンクがダウンロードされる前でも実行されます — 有料機能のゲートには CanActivate より効率的です。false を返すとそのルートは完全にスキップされ(他のマッチするルートに機会が回ります)、CanActivate ではまずチャンクをロードしてから拒否することになります。ユーザーが使えないコードのダウンロードを防ぐには CanMatch を使います。

angular
import { CanMatchFn } from '@angular/router';

export const paidFeatureGuard: CanMatchFn = (route, segments) => {
  const auth = inject(AuthService);
  // runs BEFORE the lazy chunk is even loaded
  if (auth.hasProPlan) return true;

  return inject(Router).createUrlTree(['/upgrade']);
};

// route configuration
{
  path: 'premium',
  canMatch: [paidFeatureGuard],
  loadComponent: () => import('./premium/premium.component'),
}

Resolve(データの先読み)

Resolve はルートが有効化される前に実行され、データが届くまでナビゲーションを遅らせます。解決されたデータは route.snapshot.data に入ります。コンポーネントが描画時にデータを持っていることを保証できる(空状態のちらつきがない)ので有用です。エラーはリゾルバ内で処理しましょう — EMPTY を返すとナビゲーションがキャンセルされます。ブロックしたくないロードは ngOnInit で取得します。

angular
import { ResolveFn } from '@angular/router';
import { inject } from '@angular/core';

export const userResolver: ResolveFn<User> = (route) => {
  const id = route.paramMap.get('id')!;
  return inject(UserService).getUser(+id).pipe(
    catchError(() => {
      inject(Router).navigate(['/users']);
      return EMPTY;
    }),
  );
};

// route
{ path: 'users/:id', resolve: { user: userResolver }, component: UserComponent }

// component reads pre-fetched data
export class UserComponent {
  user = this.route.snapshot.data['user'] as User;
  constructor(private route: ActivatedRoute) {}
}

ガードの組み合わせと順序

複数のガードは配列の順に実行され、最初に失敗したものがナビゲーションをキャンセルします。canMatch は遅延チャンクのロード前に、canActivate はその後に動きます。canDeactivate は離脱時に動きます。すべてのガードは同期(boolean を返す)でも非同期(Observable/Promise)でも構いません。UI をブロックするので高速に保ち、重いサーバーチェックは debounce かキャッシュを検討しましょう。

angular
// multiple guards run in declaration order, all must pass
{
  path: 'admin',
  canActivate: [authGuard, roleGuard],
  canMatch: [paidFeatureGuard],
  canDeactivate: [unsavedGuard],
  loadChildren: () => import('./admin/admin.routes'),
}

// guard returning Observable (async check)
export const roleGuard: CanActivateFn = () => {
  return inject(AuthService).hasRole('admin').pipe(
    map(ok => ok || inject(Router).parseUrl('/forbidden')),
  );
};

// ordering: canMatch → resolve → canActivate → canActivateChild
14

リゾルバ

基本のリゾルバ(ResolveFn)

ResolveFn は関数型リゾルバの API です。ナビゲーション完了前に実行され、返した値は割り当てたキーで route.data に入ります。コンポーネントは snapshot.data から同期的に読めるため、ローディング状態が不要になります。同じコンポーネントのルート間遷移でリアクティブに更新を受け取るには route.data を購読しましょう。

angular
import { ResolveFn } from '@angular/router';
import { inject } from '@angular/core';

export const postResolver: ResolveFn<Post> = (route, state) => {
  const id = Number(route.paramMap.get('id'));
  return inject(PostService).getPost(id);
};

// route
{
  path: 'posts/:id',
  resolve: { post: postResolver },
  component: PostDetailComponent,
}

// reading the resolved data
export class PostDetailComponent {
  post = this.route.snapshot.data['post'] as Post;
  constructor(private route: ActivatedRoute) {}

  // reactive: re-fetch when :id changes (same component reused)
  ngOnInit() {
    this.route.data.subscribe(d => this.post = d['post']);
  }
}

複数のリゾルバ

複数のリゾルバは並列に実行され、ルートが有効化される前にすべて完了する必要があります。resolve の各キーが route.data のキーになります。1 つでも失敗するとナビゲーションはキャンセルされます。独立したデータなら効率的です。依存関係があるならネストするか、1 つのリゾルバでチェーンしましょう。リゾルバと ngOnInit フェッチのトレードオフも検討してください。

angular
{
  path: 'dashboard',
  component: DashboardComponent,
  resolve: {
    user: userResolver,
    stats: statsResolver,
    notifications: notifResolver,
  },
}

// component
export class DashboardComponent {
  constructor(private route: ActivatedRoute) {}
  ngOnInit() {
    const { user, stats, notifications } = this.route.snapshot.data;
    // all three resolved before component loads
  }
}

リゾルバのエラーハンドリング

リゾルバのエラーは明示的に処理しましょう — 捕捉されないエラーはナビゲーションを静かにキャンセルします。EMPTY は値を出力せずにストリームを完了させ、ナビゲーションをキャンセルします。null を返せば、コンポーネントが欠損データを優雅に扱えます。404 なら not-found ルートへリダイレクトします。エラーは必ずログに残すか表面化させましょう — サイレントな失敗はデバッグが困難です。

angular
export const userResolver: ResolveFn<User | null> = (route) => {
  const id = route.paramMap.get('id')!;
  const router = inject(Router);
  const service = inject(UserService);

  return service.getUser(+id).pipe(
    catchError(err => {
      if (err.status === 404) {
        // redirect to a 'not found' page, cancel navigation
        router.navigate(['/404']);
        return EMPTY;
      }
      // re-throw other errors
      return throwError(() => err);
    }),
  );
};

リゾルバと ngOnInit フェッチの比較

リゾルバはデータが届くまでナビゲーションをブロックします — UX はきれいですが遅く感じます。ngOnInit でのフェッチはノンブロッキングですが、コンポーネントにローディング状態が必要です。モダンな Angular のガイダンスはノンブロッキング寄りです:コンポーネント内でローディングスケルトン付きのフェッチを行う方が体感性能が良くなります。データなしでは本当に描画できない場合にだけリゾルバを使いましょう。

angular
// Approach A: Resolver (blocks navigation until data arrives)
// ✅ Component renders with data — no flicker
// ❌ Slower navigation feel, blocks route transition
{
  path: 'user/:id',
  resolve: { user: userResolver },
  component: UserComponent,
}

// Approach B: Fetch in ngOnInit (non-blocking)
// ✅ Snappy navigation, show loading skeleton
// ❌ Component must handle null/loading state
export class UserComponent implements OnInit {
  user?: User;
  loading = true;
  ngOnInit() {
    this.route.params.subscribe(p => {
      this.loading = true;
      this.svc.getUser(+p['id']).subscribe(u => {
        this.user = u;
        this.loading = false;
      });
    });
  }
}

クエリパラメータとシグナル付きリゾルバ

リゾルバはルートから paramMap と queryParamMap の両方を読めます。同じコンポーネントが異なるパラメータを処理する場合は、snapshot ではなく route.data をリアクティブに購読しましょう。シグナルを使うなら、data の購読からシグナルを更新します。リゾルバとシグナルを組み合わせると、きれいでリアクティブなデータフローになります。リゾルバはナビゲーションをブロックするので重くしないこと。

angular
// read query params inside a resolver
export const searchResolver: ResolveFn<SearchResult[]> = (route) => {
  const q = route.queryParamMap.get('q') ?? '';
  const page = Number(route.queryParamMap.get('page') ?? 1);
  return inject(SearchService).search(q, page);
};

// resolver feeding a signal-based component
export class SearchComponent {
  private route = inject(ActivatedRoute);
  results = signal<SearchResult[]>([]);

  constructor() {
    this.route.data.subscribe(d => this.results.set(d['results']));
  }
}
15

アニメーション

セットアップと基本のアニメーション

provideAnimations() がアニメーションモジュールを登録します。trigger() で名前付きアニメーションを定義し、transition() で状態間の変化を宣言します。:enter と :leave は、*ngIf や @if で追加・削除される要素のための組み込み疑似状態です。テンプレートでは @triggerName で適用します。v17+ の制御フローでも @if/@for でアニメーションは動作します。

angular
// app.config.ts
import { provideAnimations } from '@angular/platform-browser/animations';
export const appConfig: ApplicationConfig = {
  providers: [provideAnimations()],
};

// component
@Component({
  selector: 'app-fade',
  animations: [
    trigger('fadeIn', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('300ms ease-in', style({ opacity: 1 })),
      ]),
      transition(':leave', [
        animate('300ms ease-out', style({ opacity: 0 })),
      ]),
    ]),
  ],
  template: `<div *ngIf="show" @fadeIn>Hello</div>`,
})

状態とトランジション

state() で静止時の名前付きスタイルを定義します。transition('a => b') は状態 a から b へのアニメーション、'<=>' は双方向です。トリガーには状態名を返す式を束縛します。状態のスタイルは即座に適用され(アニメーションなし)、トランジションがその間をアニメーションします。DOM にまだ存在しない要素には 'void'、ワイルドカードには '*' を使います。

angular
@Component({
  selector: 'app-toggle',
  animations: [
    trigger('openClose', [
      state('open', style({ height: '*', opacity: 1 })),
      state('closed', style({ height: '0', opacity: 0 })),
      transition('open => closed', animate('200ms ease-out')),
      transition('closed => open', animate('300ms ease-in')),
      // bidirectional shortcut: 'open <=> closed'
    ]),
  ],
  template: `
    <button (click)="isOpen = !isOpen">Toggle</button>
    <div [@openClose]="isOpen ? 'open' : 'closed'">Panel</div>
  `,
})
export class ToggleComponent { isOpen = false; }

キーフレームと並列アニメーション

keyframes() は offset(0〜1)付きの中間ステップを定義し、CSS の @keyframes のようにきめ細かい制御ができます。group() はアニメーションを並列に実行し、sequence() は順番に実行します。複雑な登場/退場エフェクトの構成に使いましょう。アニメーションは短く(200〜400ms)保ち、アクセシビリティのために prefers-reduced-motion を尊重してください。

angular
trigger('wiggle', [
  transition('* => *', [
    animate('600ms ease-in-out', keyframes([
      style({ transform: 'translateX(0)', offset: 0 }),
      style({ transform: 'translateX(-10px)', offset: 0.25 }),
      style({ transform: 'translateX(10px)', offset: 0.75 }),
      style({ transform: 'translateX(0)', offset: 1 }),
    ])),
  ]),
]),

// parallel/group animations
transition(':enter', [
  group([
    animate('300ms', style({ opacity: 1 })),
    animate('300ms', style({ transform: 'translateY(0)' })),
  ]),
]),

アニメーション付きリスト(@for)

@for のアイテムに :enter/:leave アニメーションを適用できます — 追加・削除時に発火します。track を設定すると Angular が変更をまたいでアイテムを正しく識別し、実際の追加/削除時(並べ替えではなく)にアニメーションが発火します。track がないとリストのアニメーションはカクつきがちです。並べ替えのアニメーションには query() と animateChild() を使います。

angular
@Component({
  selector: 'app-list',
  animations: [
    trigger('itemAnim', [
      transition(':enter', [
        style({ height: 0, opacity: 0 }),
        animate('200ms', style({ height: '*', opacity: 1 })),
      ]),
      transition(':leave', [
        animate('200ms', style({ height: 0, opacity: 0 })),
      ]),
    ]),
  ],
  template: `
    @for (item of items; track item.id) {
      <div @itemAnim>{{ item.name }}</div>
    }
  `,
})
export class AnimListComponent { items = [...]; }

ルーターアニメーション

アニメーショントリガーを router-outlet のアクティベーション状態に束縛します。query(':enter'/:leave) で入ってくる/出ていくルートコンポーネントをターゲットにします。{ optional: true } で片方が存在しない場合のエラーを防ぎます(初回ロードには :leave がない)。position: absolute でトランジション中に新旧コンポーネントを重ねます。ルートアニメーションでアプリらしい画面遷移が実現します。

angular
@Component({
  selector: 'app-root',
  animations: [
    trigger('routeAnim', [
      transition('* => *', [
        query(':enter', [
          style({ opacity: 0, position: 'absolute', width: '100%' }),
          animate('300ms', style({ opacity: 1 })),
        ], { optional: true }),
        query(':leave', [
          animate('300ms', style({ opacity: 0 })),
        ], { optional: true }),
      ]),
    ]),
  ],
  template: `
    <div [@routeAnim]="o.isActivated ? o.activatedRoute : ''">
      <router-outlet #o="outlet"></router-outlet>
    </div>
  `,
})

モーション低減と CSS アニメーション

アクセシビリティのため必ず prefers-reduced-motion を尊重しましょう — 酔いを感じるユーザーもいます。Angular アニメーションはバンドルに約 50KB 追加するため、単純なフェードなら素の CSS アニメーションで十分なこともあります。状態遷移(ステートマシン)、親子の連携、ルートアニメーションが必要なときに Angular アニメーションを使いましょう。ホバー/フェード効果なら CSS の方が軽量です。

angular
// respect prefers-reduced-motion
@Component({
  selector: 'app-safe-anim',
  animations: [
    trigger('fade', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('300ms', style({ opacity: 1 })),
      ]),
    ]),
  ],
  // or just use CSS — Angular animations add bundle weight
  template: `<div class="fade-in" @fade>Content</div>`,
  styles: [`
    @media (prefers-reduced-motion: reduce) {
      .fade-in { animation: none !important; transition: none !important; }
    }
  `],
})
16

テスト

コンポーネントテストのセットアップ

TestBed がテストモジュールを設定します。スタンドアロンコンポーネントは直接インポートでき(TestBed.configureTestingModule の declarations は不要)、createComponent が ComponentFixture を返します。クラスには .componentInstance、DOM には .nativeElement、変更検知のトリガーには .detectChanges() を使います。beforeEach と async/await で compileComponents を処理します。

angular
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';

describe('MyComponent', () => {
  let fixture: ComponentFixture<MyComponent>;
  let component: MyComponent;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [MyComponent],   // standalone components are imported
    }).compileComponents();

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();   // runs initial change detection
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

モックサービスでのテスト

テスト対象のコンポーネントを分離するため、サービスのモック実装を提供します。jasmine.createSpy() で戻り値を制御し、呼び出しを検証できます。オブジェクトのモックには useValue、クラスベースのフェイクには useClass を使います。HTTP テストでは HttpClient を HttpTestingController でオーバーライドします。モックによりテストが高速かつ決定的になり、実際のネットワーク呼び出しが不要になります。

angular
describe('UserComponent', () => {
  let mockUserService = {
    getUsers: jasmine.createSpy().and.returnValue(of([...])),
    addUser: jasmine.createSpy().and.returnValue(of({})),
  };

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [UserComponent],
      providers: [
        { provide: UserService, useValue: mockUserService },
      ],
    }).compileComponents();
  });

  it('loads users on init', () => {
    const fixture = TestBed.createComponent(UserComponent);
    fixture.detectChanges();
    expect(mockUserService.getUsers).toHaveBeenCalled();
    expect(fixture.componentInstance.users.length).toBe(2);
  });
});

HTTP テスト

HttpTestingController はテスト内で HttpClient の呼び出しを傍受します — 実際のネットワークは発生しません。expectOne でリクエストの発生を検証して取得し、flush() でサーバーレスポンスをシミュレートします。verify() で未処理のリクエストがないことを確認します。成功とエラーの両経路をテストしましょう:{ status: 500, statusText: 'Server Error' } のようなステータスコード付きで flush するとエラーをシミュレートできます。

angular
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideHttpClient } from '@angular/common/http';

describe('PostService', () => {
  let service: PostService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        PostService,
        provideHttpClient(),
        provideHttpClientTesting(),
      ],
    });
    service = TestBed.inject(PostService);
    httpMock = TestBed.inject(HttpTestingController);
  });

  it('fetches posts', () => {
    service.getPosts().subscribe(posts => expect(posts.length).toBe(2));

    const req = httpMock.expectOne('/api/posts');
    expect(req.request.method).toBe('GET');
    req.flush([{ id: 1 }, { id: 2 }]);   // simulate response
    httpMock.verify();                    // no outstanding requests
  });
});

テンプレートとインタラクションのテスト

fixture.nativeElement で生の DOM にアクセスして検証できます。プロパティ設定後のテンプレート束縛の同期には detectChanges() を呼びます。spyOn でメソッド呼び出しを検証できます。コンポーネント内部のクエリには debugElement.query(By.css()) が型安全です。イベントはネイティブ DOM メソッド(click())か、カスタムイベントなら DebugElement.triggerEventHandler で発火させます。

angular
it('renders the title', () => {
  const fixture = TestBed.createComponent(MyComponent);
  fixture.componentInstance.title = 'Hello';
  fixture.detectChanges();
  const el: HTMLElement = fixture.nativeElement;
  expect(el.querySelector('h1')?.textContent).toContain('Hello');
});

it('calls save on button click', () => {
  const fixture = TestBed.createComponent(MyComponent);
  const spy = spyOn(fixture.componentInstance, 'save');
  const button = fixture.nativeElement.querySelector('button');
  button.click();
  expect(spy).toHaveBeenCalled();
});

// By.css for debug element queries (faster than nativeElement)
const debugEl = fixture.debugElement.query(By.css('.submit'));

シグナルのテスト

シグナルは関数です — テストでは括弧付きで呼び出して値を読みます。set() で書き込み可能なシグナルを直接更新でき、間接的な操作が不要です。シグナル駆動のテンプレートの同期には detectChanges() を使います。computed/effect については、detectChanges や TestBed.flushEffects() で依存する effect が確実に実行されるようにします。シグナルによりテストはより同期的で予測しやすくなります。

angular
describe('CounterComponent', () => {
  it('increments count', () => {
    const fixture = TestBed.createComponent(CounterComponent);
    const comp = fixture.componentInstance;

    expect(comp.count()).toBe(0);
    comp.increment();
    expect(comp.count()).toBe(1);

    // force signal effects to run in tests
    fixture.detectChanges();
  });

  it('renders count in template', () => {
    const fixture = TestBed.createComponent(CounterComponent);
    fixture.componentInstance.count.set(5);
    fixture.detectChanges();   // syncs signal to template
    expect(fixture.nativeElement.textContent).toContain('5');
  });
});

Cypress / Playwright での E2E

E2E テストは実際のブラウザでアプリ全体を動かします。セレクタには data-cy 属性を使いましょう — 安定していて CSS クラスと結合しません。Cypress はブラウザ内で動き、Playwright は複数ブラウザで動きます。ng e2e を使うか、Cypress/Playwright を手動設定します。E2E はユニットテストが見逃す統合問題を検出しますが遅いので、スイートを絞り込みましょう。

angular
// cypress test (cypress/e2e/login.cy.ts)
describe('Login flow', () => {
  beforeEach(() => cy.visit('/login'));

  it('logs in with valid credentials', () => {
    cy.get('[data-cy=email]').type('[email protected]');
    cy.get('[data-cy=password]').type('secret123');
    cy.get('[data-cy=submit]').click();

    cy.url().should('include', '/dashboard');
    cy.contains('Welcome, User');
  });
});

// run with: npx cypress open  (interactive)
//           npx cypress run   (headless CI)
17

PWA

PWA サポートの追加

ng add @angular/pwa で必要なものがすべて揃います:Service Worker の登録、Web マニフェスト、アイコン。Service Worker は本番ビルド(ng build --configuration production)でのみ動き、開発環境では予期しないキャッシュを避けるため無効です。registrationStrategy で SW の登録タイミングを制御でき、registerWhenStable はアプリが安定するのを待ちます。

angular
# add @angular/service-worker
ng add @angular/pwa --project my-app

# this generates:
# - ngsw-config.json (service worker config)
# - manifest.webmanifest
# - icons in src/assets/icons/
# - registers service worker in app.config.ts

# app.config.ts (auto-updated)
export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideServiceWorker('ngsw-worker.js', {
      enabled: environment.production,
      registrationStrategy: 'registerWhenStable:30000',
    }),
  ],
};

Service Worker 設定(ngsw-config.json)

assetGroups はアプリシェル(prefetch)と静的アセット(lazy)をキャッシュします。dataGroups は鮮度/性能戦略と TTL を指定して API レスポンスをキャッシュします。prefetch は先回りでダウンロードし、lazy は必要時にダウンロードします。freshness はまずネットワークを試して失敗時にキャッシュへ(新鮮なデータ向け)、performance はまずキャッシュを使います(ほぼ静的なデータ向け)。

angular
{
  "$schema": "./node_modules/@angular/service-worker/config/schema.json",
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "updateMode": "prefetch",
      "resources": {
        "files": ["/favicon.ico", "/index.html", "/manifest.webmanifest", "/*.css", "/*.js"]
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": { "files": ["/assets/**", "/*.(svg|png|jpg|jpeg|webp|woff2)"] }
    }
  ],
  "dataGroups": [
    {
      "name": "api",
      "urls": ["https://api.example.com/**"],
      "cacheConfig": {
        "maxSize": 100, "maxAge": "1d", "timeout": "10s", "strategy": "freshness"
      }
    }
  ]
}

更新の処理

SwUpdate は新しいバージョンが利用可能になったときに通知します。VERSION_READY は新しいバンドルがダウンロードされ有効化の準備ができたことを意味します。activateUpdate() で新バージョンへ切り替え、反映にはリロードします。重要な更新は即時強制有効化し、そうでなければユーザーに促しましょう。versionUpdates を購読して VERSION_DETECTED、VERSION_READY、NO_NEW_VERSION_DETECTED を処理します。

angular
import { SwUpdate } from '@angular/service-worker';
import { inject } from '@angular/core';

export class UpdatePromptComponent {
  private updates = inject(SwUpdate);
  updateAvailable = false;

  constructor() {
    this.updates.versionUpdates.subscribe(evt => {
      if (evt.type === 'VERSION_READY') {
        this.updateAvailable = true;
      }
    });
  }

  applyUpdate() {
    this.updates.activateUpdate().then(() => document.location.reload());
  }
}

オフライン対応とキャッシュ

SwPush は Service Worker 経由の Web プッシュ通知を有効にします。requestSubscription がユーザーに許可を求め、サーバーへ送るサブスクリプションオブジェクトを返します。SW はタブが閉じていても push イベントを受け取ります。VAPID キーでサーバーを認証します。メッセージ表示には Notification API と組み合わせ、クリックでアプリ内ナビゲーションを処理しましょう。

angular
import { SwPush } from '@angular/service-worker';

export class NotificationComponent {
  private swPush = inject(SwPush);

  subscribeToPush() {
    this.swPush.requestSubscription({
      serverPublicKey: this.VAPID_PUBLIC,
    }).then(sub => this.sendToServer(sub))
      .catch(err => console.error('Push denied', err));
  }

  // check if SW is enabled
  ngOnInit() {
    if (!this.swPush.isEnabled) {
      console.warn('Push notifications not supported');
    }
  }
}

アプリマニフェスト

Web マニフェストによりアプリがインストール可能になります(ホーム画面に追加)。name/short_name はホーム画面に表示され、theme_color はブラウザ UI を着色し、display: standalone はブラウザの UI を取り除いてアプリらしくします。複数サイズのアイコン(192、512)に加え、Android 用の maskable アイコンも用意しましょう。インストール可能性の検証には Lighthouse の PWA 監査を使います。

angular
<!-- index.html (added by ng add @angular/pwa) -->
<link rel="manifest" href="manifest.webmanifest">
<meta name="theme-color" content="#1976d2">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="apple-touch-icon" href="assets/icons/icon-152x152.png">

// manifest.webmanifest
{
  "name": "My App",
  "short_name": "MyApp",
  "theme_color": "#1976d2",
  "background_color": "#fafafa",
  "display": "standalone",
  "scope": "/",
  "start_url": "/",
  "icons": [
    { "src": "assets/icons/icon-192x192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "assets/icons/icon-512x512.png", "sizes": "512x512", "type": "image/png" }
  ]
}

インストール可能性と Lighthouse

beforeinstallprompt は Chrome でアプリがインストール可能になったときに発火し、ネイティブのプロンプトを先送りできます。イベントを保存し、ユーザーの操作(ボタンクリック)から prompt() を呼び出しましょう。iOS Safari はこのイベントを発火しないため、ユーザーは共有メニューからインストールします。Lighthouse の PWA 監査でインストール可能性を検証しましょう。PWA は Service Worker がアプリシェルをキャッシュしているときだけオフラインで動作します。

angular
// detect install prompt (Chrome)
let deferredPrompt: any;
window.addEventListener('beforeinstallprompt', (e) => {
  e.preventDefault();
  deferredPrompt = e;
  this.canInstall = true;   // show "Install App" button
});

// user-triggered install (must be from user gesture)
async installApp() {
  if (!deferredPrompt) return;
  deferredPrompt.prompt();
  const { outcome } = await deferredPrompt.userChoice;
  console.log('Install:', outcome);
  deferredPrompt = null;
}

// Lighthouse PWA checklist:
// ✅ served over HTTPS
// ✅ registers a service worker
// ✅ has a web manifest with icons
// ✅ start_url loads offline
18

スタンドアロンコンポーネント

スタンドアロンのブートストラップ

bootstrapApplication は NgModule なしでスタンドアロンアプリを起動します。ルートの AppComponent はスタンドアロンである必要があります。app.config.ts にプロバイダ(ルーター、HTTP、アニメーション、zone 設定)を集約します。v17 以降はこれがデフォルトです。各 provideX() 関数がサブシステムを配線します。AppModule + プロバイダよりずっときれいです。

angular
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, appConfig)
  .catch(err => console.error(err));

// app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideHttpClient(),
  ],
};

スタンドアロンコンポーネントのインポート

standalone: true でコンポーネントが自己完結であることを示します。imports 配列にはテンプレートが必要とするすべて(モジュール、コンポーネント、ディレクティブ、パイプ)を列挙します。v17+ の制御フロー(@if/@for)ならそれらのために CommonModule は不要です。使用するものだけをインポートして tree-shaking を改善しましょう。スタンドアロンコンポーネントは NgModule の exports 経由でも使えます。

angular
@Component({
  selector: 'app-user-list',
  standalone: true,
  imports: [
    CommonModule,          // *ngIf, *ngFor, pipes (or use built-in @if/@for)
    FormsModule,           // ngModel
    UserCardComponent,     // another standalone component
    HighlightDirective,    // standalone directive
    TruncatePipe,          // standalone pipe
  ],
  template: `
    <input [(ngModel)]="filter" />
    @for (u of users; track u.id) {
      <app-user-card [user]="u" appHighlight>{{ u.name | truncate:20 }}</app-user-card>
    }
  `,
})
export class UserListComponent { ... }

スタンドアロンのルートと遅延ロード

loadComponent は単一のスタンドアロンコンポーネントを遅延ロードします — 最小のチャンクです。loadChildren はルートファイル(Routes のデフォルトエクスポート)を遅延ロードします。どちらも動的 import() を使い、バンドラが分割できるよう静的パスで指定します。これでフィーチャーモジュールは完全に置き換えられます。各遅延ルートは独自の JS ファイルになり、初回ナビゲーション時にロードされます。

angular
export const routes: Routes = [
  { path: '', loadComponent: () => import('./home/home.component')
      .then(m => m.HomeComponent) },
  {
    path: 'admin',
    loadComponent: () => import('./admin/admin.component')
      .then(m => m.AdminComponent),
    canMatch: [authGuard],
  },
  {
    path: 'reports',
    loadChildren: () => import('./reports/reports.routes')
      .then(m => m.REPORTS_ROUTES),
  },
];

スタンドアロンとしてのディレクティブとパイプ

ディレクティブとパイプもスタンドアロンにできます(v15+)。standalone: true を付けて、必要なコンポーネントにインポートしましょう。共有モジュールで宣言する必要がなくなります。後方互換のため、スタンドアロンのディレクティブ/パイプは NgModule の exports に追加して NgModule ベースのコンポーネントから使うことも可能です。

angular
@Directive({
  selector: '[appHighlight]',
  standalone: true,
})
export class HighlightDirective { ... }

@Pipe({
  name: 'truncate',
  standalone: true,
})
export class TruncatePipe implements PipeTransform { ... }

// use directly in a standalone component's imports
@Component({
  imports: [HighlightDirective, TruncatePipe],
  template: `<p appHighlight>{{ text | truncate:10 }}</p>`,
})

NgModule からの移行

schematic が移行を自動化します:すべての宣言をスタンドアロンにし、NgModule の imports を各コンポーネントの imports 配列へ移動し、不要になったモジュールを削除します。部分的に実行できるので段階的に進めましょう。移行後は AppRoutingModule や AppModule を削除し、bootstrapApplication を使えます。結果としてより軽く tree-shaking 可能なアプリになります。

angular
# automatic migration (v15.2+)
ng generate @angular/core:standalone

# options:
# 1. Convert all components/directives/pipes to standalone
# 2. Remove unnecessary NgModule classes
# 3. Bootstrap the app using bootstrapApplication

// before: declared in a module
@NgModule({
  declarations: [OldComponent],
  imports: [CommonModule],
  exports: [OldComponent],
})
export class OldModule {}

// after: standalone component
@Component({
  standalone: true,
  imports: [CommonModule],
  // ...
})
export class OldComponent {}

スタンドアロンのプロバイダへの注入

スタンドアロンアプリでは AppModule の代わりに app.config.ts でプロバイダを設定します。APP_INITIALIZER はブートストラップ前にセットアップを実行します。コンポーネントレベルのプロバイダはそのサブツリーにスコープされます。サービスには引き続き providedIn: 'root' が推奨です — tree-shaking 可能です。providers 配列はサービス以外の値(トークン、設定、モック)に使いましょう。

angular
// app.config.ts — global providers
export const appConfig: ApplicationConfig = {
  providers: [
    { provide: API_URL, useValue: 'https://api.example.com' },
    { provide: ErrorHandler, useClass: GlobalErrorHandler },
    { provide: APP_INITIALIZER, multi: true, useFactory: () => initApp },
  ],
};

// component-level providers (scoped to this component and children)
@Component({
  providers: [
    { provide: UserService, useClass: MockUserService },
  ],
})
export class AdminComponent {}

// tree-shakable service
@Injectable({ providedIn: 'root' })  // preferred over providers array
export class AuthService {}
19

シグナル

シグナルの作成

signal() はリアクティブな値を作ります。呼び出して読みます:count()。set()(置き換え)か update()(前の値から計算)で更新します。シグナルは同期的で、単純な状態なら Observable のオーバーヘッドを避けられます。テンプレートでは () 付きで呼べます — v17.2+ では一部のコンテキストで自動的にアンラップもされます。シグナルは OnPush 変更検知と統合されています。

angular
import { signal, computed, effect } from '@angular/core';

export class CounterComponent {
  // writable signal with initial value
  count = signal(0);
  user = signal<User | null>(null);

  // reading: call the signal as a function
  current = this.count();    // 0

  // writing
  increment() { this.count.update(v => v + 1); }
  setFive() { this.count.set(5); }

  // in templates, signals are called automatically in v17.2+
  // {{ count }} or {{ count() }} both work in templates
}

Computed シグナル

computed() は依存関係を自動追跡して値をキャッシュする派生的で読み取り専用のシグナルを作ります。依存関係が変わり、かつ再び読まれたときにだけ再計算されます(遅延評価)。Computed シグナルは他の computed シグナルに依存でき、グラフを形成します。メソッドと違い結果をキャッシュします。RxJS combineLatest の多くの用途を置き換えます。

angular
export class CartComponent {
  items = signal<Item[]>([]);
  taxRate = signal(0.08);

  // derived state — recomputes only when items or taxRate change
  subtotal = computed(() =>
    this.items().reduce((sum, i) => sum + i.price * i.qty, 0)
  );
  tax = computed(() => Math.round(this.subtotal() * this.taxRate() * 100) / 100);
  total = computed(() => this.subtotal() + this.tax());

  // computed signals are readonly and cached
  // they recompute lazily only when read AND a dependency changed
}

Effect(副作用)

effect() はシグナルの依存関係が変わったときに副作用を実行します。ロギング、localStorage への同期、データ取得、DOM 操作に使いましょう。Effect は変更検知の後に実行されます。同じ effect 内で読んだシグナルへ書き込むのは避けましょう — 無限ループになります。onCleanup で次回実行前の後始末を登録できます。Effect は注入コンテキスト内で作る必要があります。

angular
export class SearchComponent {
  query = signal('');
  results = signal<Result[]>([]);

  constructor() {
    // effect runs when its signal dependencies change
    effect(() => {
      const q = this.query();
      // ⚠️ avoid setting signals read in this effect (causes loops)
      this.search(q).then(r => this.results.set(r));
    });
  }

  // effect with cleanup
  private log = effect((onCleanup) => {
    const id = setInterval(() => console.log(this.count()), 1000);
    onCleanup(() => clearInterval(id));
  });
}

テンプレート内のシグナル(OnPush)

シグナルは OnPush とシームレスに統合されます — Angular はどのビューがシグナルに依存するかを正確に知り、変化したときにはそのビューだけをチェック対象にします。手動の markForCheck() は不要です。テンプレートでは () 付きでシグナルを呼んで読みます。OnPush + シグナルは最も効率的な変更検知の構成で、zone.js を完全に捨てられることも多いです(ゾーンレスモード)。

angular
@Component({
  selector: 'app-todo',
  // signals work great with OnPush — automatic efficiency
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <input (input)="text.set($any($event.target).value)" />
    <p>You typed: {{ text() }}</p>
    <p>Length: {{ length() }}</p>
    <button (click)="clear()">Clear</button>
  `,
})
export class TodoComponent {
  text = signal('');
  length = computed(() => this.text().length);
  clear() { this.text.set(''); }
}

シグナル入力とクエリ

input()/input.required() は読み取り専用のシグナル入力を作ります。output() は型付きの出力、model() は双方向バインド可能なシグナル入力(xChange 出力が自動生成)です。viewChild()/contentChild() はビュー初期化後に解決されるシグナルを返します — () 付きで呼んで読みます。これらのモダン API は @Input/@Output/@ViewChild デコレータをリアクティブなシグナルで置き換えます。

angular
import { input, output, viewChild, contentChild, model } from '@angular/core';

export class EditComponent {
  // signal input (readonly, v17.1+)
  id = input<number>(0);
  requiredName = input.required<string>();

  // signal output (v17.3+)
  saved = output<User>();

  // two-way signal (v17.2+)
  value = model<number>(0);   // creates input + output named valueChange

  // signal queries
  inputEl = viewChild<ElementRef>('input');      // in own template
  header = contentChild<TemplateRef>('header');  // projected content

  focus() { this.inputEl()?.nativeElement.focus(); }
}

シグナルと RxJS の相互運用

toSignal は Observable をシグナルに変換します(1 回購読し、破棄時に解除)。toObservable はその逆です。シグナル(同期状態向け)と RxJS(debounce した検索のような複雑な非同期フロー向け)を混ぜるには相互運用を使いましょう。takeUntilDestroyed は DestroyRef 経由で自動購読解除します。initialValue で最初の出力前の undefined 読み取りを防げます。注入コンテキストが必要です。

angular
import { toSignal, toObservable, takeUntilDestroyed } from '@angular/core/rxjs-interop';

export class SearchComponent {
  private http = inject(HttpClient);

  // Observable → Signal (one-way)
  results = toSignal(this.http.get<Result[]>('/api/results'), {
    initialValue: [] as Result[],
  });

  // Signal → Observable (for RxJS operators)
  private query$ = toObservable(this.query);

  // combine the best of both worlds
  filtered = toSignal(
    this.query$.pipe(
      debounceTime(300),
      switchMap(q => this.http.get(`/api/search?q=${q}`)),
      takeUntilDestroyed(),
    ),
    { initialValue: [] as Result[] },
  );
}
20

NgModule とアーキテクチャ

NgModule の構造

NgModule はアプリを凝集したブロックに整理します。declarations はモジュールが所有するもの、imports は他モジュールの exports の取り込み、exports は宣言を取り込み側へ公開します。bootstrap を設定するのはルートモジュールだけです。モダンな Angular はスタンドアロンコンポーネントを推奨しますが、NgModule のアプリは依然存在します。古いコードベースや一部のライブラリで使われているため、両方を理解しましょう。

angular
@NgModule({
  declarations: [                  // components, directives, pipes owned by this module
    AppComponent,
    UserListComponent,
    HighlightDirective,
    TruncatePipe,
  ],
  imports: [                       // other modules whose exports this module needs
    BrowserModule,
    FormsModule,
    HttpClientModule,
    AppRoutingModule,
  ],
  exports: [                       // what's visible to modules that import this module
    UserListComponent,
    TruncatePipe,
  ],
  providers: [],                   // services (use providedIn: 'root' instead)
  bootstrap: [AppComponent],       // only in the root module
})
export class AppModule {}

フィーチャーモジュールと共有モジュール

SharedModule は共通 UI コンポーネント/ディレクティブ/パイプをまとめ、機能をまたいで再利用します — CommonModule と FormsModule を再エクスポートすれば取り込み側の手間が減ります。フィーチャーモジュールは機能領域をカプセル化し、forChild() により同じモジュールを取り込みごとに異なる設定(ルーティングなど)で使えます。スタンドアロンアプリでは共有モジュールより個別のスタンドアロンコンポーネントを推奨します。

angular
// shared.module.ts — reusable UI bits
@NgModule({
  imports: [CommonModule, FormsModule],
  declarations: [ButtonComponent, CardComponent, HighlightDirective],
  exports: [ButtonComponent, CardComponent, HighlightDirective, FormsModule],
})
export class SharedModule {}

// feature module (lazy-loaded)
@NgModule({
  declarations: [AdminComponent, AdminUsersComponent],
  imports: [CommonModule, RouterModule, SharedModule],
  exports: [AdminComponent],
})
export class AdminModule {
  static forChild(): ModuleWithProviders<AdminModule> {
    return { ngModule: AdminModule, providers: [AdminService] };
  }
}

Core Module とシングルトンサービス

CoreModule はアプリ全体のシングルトン(サービス、インターセプター、エラーハンドラ)を保持し、AppModule で 1 回だけインポートします。コンストラクタのガードは誤って再インポートされるのを防ぎます(するとサービスの重複インスタンスが生まれます)。スタンドアロンアプリではこれらのプロバイダは app.config.ts へ移ります。CoreModule パターンはレガシーですが、v14 以前のコードベースでは出会います。

angular
// core.module.ts — app-wide singletons, imported once in AppModule
@NgModule({
  providers: [
    AuthService,
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
    { provide: ErrorHandler, useClass: GlobalErrorHandler },
  ],
})
export class CoreModule {
  // guard against importing twice
  constructor(@Optional() @SkipSelf() parent?: CoreModule) {
    if (parent) throw new Error('CoreModule already loaded');
  }
}

forRoot と forChild のパターン

forRoot はルートインスタンスを設定し(AppModule で 1 回呼ぶ)、forChild は子ルートを登録します(フィーチャーモジュールで呼ぶ)。このパターンは RouterModule や設定が必要なライブラリモジュールで使われます。モダンな Angular では app.config.ts の provideX() 関数に置き換えられました。サードパーティライブラリでは今も見かけるので、統合のために理解しておきましょう。

angular
// classic RouterModule pattern
@NgModule({ imports: [CommonModule], exports: [RouterModule] })
export class RouterModule {
  static forRoot(routes: Routes): ModuleWithProviders<RouterModule> {
    return {
      ngModule: RouterModule,
      providers: [provideRouter(routes)],
    };
  }
  static forChild(routes: Routes): ModuleWithProviders<RouterModule> {
    return { ngModule: RouterModule, providers: [provideRoutes(routes)] };
  }
}

// AppModule imports: RouterModule.forRoot(ROUTES)
// FeatureModule imports: RouterModule.forChild(FEATURE_ROUTES)

// modern equivalent: provideRouter(routes) in app.config.ts

Entry Components と動的生成

entryComponents(非推奨)は動的に生成されるコンポーネント(ダイアログ、モーダル)を列挙していました。モダンな Angular は ViewContainerRef.createComponent() や NgComponentOutlet を使い、登録は不要です。スタンドアロンコンポーネントともシームレスに動きます。createComponent は .instance と .destroy() を持つ ComponentRef を返します。リークを避けるため destroy() を呼んで後始末しましょう。

angular
// older API: entryComponents for dynamically created components
@NgModule({
  entryComponents: [DialogComponent, ModalComponent],
})
export class AppModule {}

// modern: ViewContainerRef.createComponent (no entryComponents needed)
export class DialogService {
  constructor(private vcr: ViewContainerRef) {}

  open() {
    const ref = this.vcr.createComponent(DialogComponent);
    ref.instance.title = 'Hello';
    ref.instance.close.subscribe(() => ref.destroy());
    return ref;
  }
}

// even simpler: NgComponentOutlet in template
<ng-container *ngComponentOutlet="dialogComponent; inputs: { title: 'Hi' }" />

遅延ロードされるモジュール

遅延ロードされるモジュールはナビゲーション時に読み込まれる独立した JS チャンクになります。動的 import() はバンドラが分割できるよう静的文字列である必要があります。遅延モジュールには独自のルートインジェクタがあるため、その中で providedIn を指定したサービスはアプリ全体のシングルトンにはなりません。モダンなスタンドアロンアプリではより単純で粒度の細かい、ルートファイル + loadComponent/loadChildren を使います。

angular
// classic lazy module (pre-standalone)
const routes: Routes = [
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
  },
];

// admin-routing.module.ts
const routes: Routes = [
  { path: '', component: AdminComponent },
  { path: 'users', component: AdminUsersComponent },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class AdminRoutingModule {}

// admin.module.ts
@NgModule({
  declarations: [AdminComponent, AdminUsersComponent],
  imports: [CommonModule, AdminRoutingModule],
})
export class AdminModule {}

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.