angular-viewchild について
Angular コンポーネントのクエリに関するリファレンススキルです。要素や投影コンテンツへのアクセス、クエリのタイミングとオプションを扱います。
主な機能
- 01ViewChild による要素参照
- 02ContentChild による投影コンテンツ取得
- 03静的・動的クエリのタイミング
- 04複数要素向けの ViewChildren
- 05read オプションによるクエリトークン指定
- 06子コンポーネントインスタンスへのアクセス
活用シーン
- 01ビュー初期化後の要素フォーカス
- 02コンポーネントに投影されたコンテンツへのアクセス
- 03テンプレートやビューコンテナの取得
- 04該当する子要素の反復処理
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ oguzhan18/ angular-ecosystem-skills --skill angular-viewchildインストール後、Claude Code で/angular-viewchildを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/discussions/_INDEX.mdreferences/docs/_INDEX.mdreferences/issues/_INDEX.mdreferences/releases/_INDEX.md詳細
Angular ViewChild / ContentChild
バージョン: Angular 21(2025) タグ: ViewChild、ContentChild、DOM、クエリ
参考資料: ViewChild API • ContentChild API
ベストプラクティス
- 要素参照には ViewChild を使用します
import { ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({})
export class MyComponent implements AfterViewInit {
@ViewChild('input') inputEl!: ElementRef<HTMLInputElement>;
ngAfterViewInit() {
this.inputEl.nativeElement.focus();
}
}
- static オプションを使用します
// Static - available in ngOnInit
@ViewChild('static', { static: true }) staticEl!: ElementRef;
// Dynamic - available in ngAfterViewInit
@ViewChild('dynamic', { static: false }) dynamicEl!: ElementRef;
- 投影されたコンテンツには ContentChild を使用します
import { ContentChild, TemplateRef } from '@angular/core';
@Component({
selector: 'app-card',
template: `
<div class="card">
<ng-content></ng-content>
</div>
`
})
export class CardComponent {
@ContentChild(TemplateRef) headerTemplate!: TemplateRef<any>;
}
- 複数の要素には ViewChildren を使用します
import { ViewChildren, QueryList } from '@angular/core';
@Component({})
export class ListComponent {
@ViewChildren('item') items!: QueryList<ElementRef>;
ngAfterViewInit() {
this.items.forEach(item => console.log(item));
}
}
- read オプションを使用します
@ViewChild('component', { read: ViewContainerRef }) container!: ViewContainerRef;
@ViewChild('template', { read: TemplateRef }) template!: TemplateRef<any>;
- コンポーネントのインスタンスにアクセスします
@ViewChild(ChildComponent) child!: ChildComponent;
ngAfterViewInit() {
this.child.doSomething();
}
- シグナルと併用します
@ViewChild('el') el!: ElementRef<HTMLElement>;
ngAfterViewInit() {
effect(() => {
if (this.shouldFocus()) {
this.el.nativeElement.focus();
}
});
}
コメント
Markdown 対応