angular-lifecycle について
Angular 21でコンポーネントを実装する開発者向けのライフサイクルフック解説スキルです。初期化、変更処理、クリーンアップに使うフックと基本パターンを紹介します。
主な機能
- 01初期化とクリーンアップの指針
- 02入力変更への対応
- 03ビューと投影コンテンツのフック
- 04カスタム変更検知
- 05OnPushとフックの併用
活用シーン
- 01コンポーネント初期化のフック選択
- 02コンポーネント入力変更への対応
- 03破棄時のサブスクリプション解放
- 04ビュー初期化後のDOMアクセス
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ oguzhan18/ angular-ecosystem-skills --skill angular-lifecycleインストール後、Claude Code で/angular-lifecycleを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/discussions/_INDEX.mdreferences/docs/_INDEX.mdreferences/issues/_INDEX.mdreferences/releases/_INDEX.md詳細
Angular のライフサイクルフック
バージョン: Angular 21(2025) タグ: ライフサイクル、フック、ngOnInit、ngOnChanges
参考資料: ライフサイクルフック • API
ベストプラクティス
- 初期化には OnInit を使用します
import { OnInit } from '@angular/core';
@Component({})
export class MyComponent implements OnInit {
ngOnInit() {
// Initialize data, call services
this.loadData();
}
}
- クリーンアップには OnDestroy を使用します
import { OnDestroy } from '@angular/core';
@Component({})
export class MyComponent implements OnDestroy {
private destroy$ = new Subject<void>();
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
- 入力の変更には OnChanges を使用します
import { OnChanges, SimpleChanges } from '@angular/core';
@Component({})
export class MyComponent implements OnChanges {
@Input() data: any;
ngOnChanges(changes: SimpleChanges) {
if (changes['data']) {
console.log('Data changed:', this.data);
}
}
}
- DOM 操作には AfterViewInit を使用します
import { AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({})
export class MyComponent implements AfterViewInit {
@ViewChild('el') el!: ElementRef;
ngAfterViewInit() {
this.el.nativeElement.focus();
}
}
- 投影されたコンテンツには AfterContentInit を使用します
import { AfterContentInit, ContentChild } from '@angular/core';
@Component({})
export class MyComponent implements AfterContentInit {
@ContentChild('header') header!: ElementRef;
ngAfterContentInit() {
// Access projected content
}
}
- カスタムの変更検知には DoCheck を使用します
import { DoCheck } from '@angular/core';
@Component({})
export class MyComponent implements DoCheck {
ngDoCheck() {
// Custom change detection
}
}
- ライフサイクルフックとともに OnPush を使用します
@Component({
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
@Input() data: any;
ngOnChanges(changes: SimpleChanges) {
// OnPush needs explicit change detection trigger
}
}
- constructor と ngOnInit を使い分けます
// Constructor - for dependency injection only
constructor(private service: MyService) {}
// ngOnInit - for initialization logic
ngOnInit() {
this.data = this.service.getData();
}
コメント
Markdown 対応