mcpField
A
angular-viewchild

angular-viewchild

github.com/oguzhan18開発7174 回インストール31 週間前に更新
リポジトリ

angular-viewchild について

Angular コンポーネントのクエリに関するリファレンススキルです。要素や投影コンテンツへのアクセス、クエリのタイミングとオプションを扱います。

主な機能

  1. 01ViewChild による要素参照
  2. 02ContentChild による投影コンテンツ取得
  3. 03静的・動的クエリのタイミング
  4. 04複数要素向けの ViewChildren
  5. 05read オプションによるクエリトークン指定
  6. 06子コンポーネントインスタンスへのアクセス

活用シーン

  1. 01ビュー初期化後の要素フォーカス
  2. 02コンポーネントに投影されたコンテンツへのアクセス
  3. 03テンプレートやビューコンテナの取得
  4. 04該当する子要素の反復処理

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/oguzhan18/angular-ecosystem-skills --skill angular-viewchild

インストール後、Claude Code で/angular-viewchildを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/discussions/
_INDEX.md
references/docs/
_INDEX.md
references/issues/
_INDEX.md
references/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();
    }
  });
}

コメント