どちらも子要素/コンポーネントへの参照を検索しますが、異なる場所を見ます:@ViewChildはコンポーネント自身のテンプレートをクエリし、一方@ContentChildはを介してコンポーネントに投影されたコンテンツをクエリします。
<ng-content>@Component({
template: `
<input #nameInput /> <!-- a template reference in MY template -->
<app-child></app-child>
`,
})
export class ParentComponent implements AfterViewInit {
@ViewChild("nameInput") input!: ElementRef; // by template ref
@ViewChild(ChildComponent) child!: ChildComponent; // by component type
ngAfterViewInit() {
this.input.nativeElement.focus(); // available after the VIEW initializes
this.child.doSomething(); // call a child component's method
}
}
@ViewChildはコンポーネント自身がテンプレートに宣言した要素/コンポーネントにアクセスします — **ngAfterViewInit**で利用可能です。
@Component({
selector: "app-card",
template: `<div class="card"><ng-content></ng-content></div>`, // content projected here
})
export class CardComponent implements AfterContentInit {
@ContentChild(CardTitleComponent) title!: CardTitleComponent;
ngAfterContentInit() {
// the projected content is ready here (EARLIER than ngAfterViewInit)
console.log(this.title);
}
}
<!-- parent projects content INTO app-card -->
<app-card>
<app-card-title>Hello</app-card-title> <!-- this is what ContentChild finds -->
</app-card>
@ContentChildは親が渡したコンテンツ(<ng-content>を通じて投影されたもの)にアクセスします — **ngAfterContentInit**で利用可能です。
@ViewChild → elements in THIS component's own template → ngAfterViewInit
@ContentChild → elements PROJECTED in from the parent → ngAfterContentInit
(plural: @ViewChildren / @ContentChildren return a QueryList of all matches)
@ViewChildren(ItemComponent) items!: QueryList<ItemComponent>; // all matching items
ngAfterViewInit() { this.items.forEach(i => ...); this.items.changes.subscribe(...); }
input = viewChild<ElementRef>("nameInput"); // signal-based query (newer Angular)
@ViewChild(自分のテンプレート)と@ContentChild(投影されたコンテンツ)を区別すること — および各々のライフサイクルタイミング(ngAfterViewInit vs ngAfterContentInit) — は、自分のテンプレート要素またはコンシューマが投影するコンテンツのいずれかと相互作用する必要があるような再利用可能なコンポーネントを構築する際に不可欠です。
これはコンポーネントライブラリ、タブ、フォームコントロール、および子要素と調整する必要があるラッパーを作成する際の、混乱の一般的なポイントであり、頻繁に必要とされます。