दोनों बाल तत्वों/घटकों के संदर्भों के लिए खोज करते हैं, लेकिन वे विभिन्न स्थानों को देखते हैं: @ViewChild घटक के अपने template को खोजता है, जबकि के माध्यम से घटक में सामग्री को खोजता है।
दोनों बाल तत्वों/घटकों के संदर्भों के लिए खोज करते हैं, लेकिन वे विभिन्न स्थानों को देखते हैं: @ViewChild घटक के अपने template को खोजता है, जबकि के माध्यम से घटक में सामग्री को खोजता है।
@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 उन तत्वों/घटकों तक पहुंचता है जो घटक स्वयं अपने template में घोषित करता है — 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 (आपका template) को @ContentChild (प्रजेक्ट की गई सामग्री) से अलग करना — और उनके संबंधित lifecycle timings (ngAfterViewInit vs ngAfterContentInit) — पुन: प्रयोग योग्य घटक बनाते समय आवश्यक है जिन्हें अपने template तत्वों या ऐसी सामग्री के साथ इंटरैक्ट करने की आवश्यकता है जो उपभोक्ता उनमें प्रजेक्ट करते हैं।
यह आम भ्रम का बिंदु है और घटक लाइब्रेरीज़, tabs, form controls, और wrappers बनाते समय एक लगातार आवश्यकता है जिन्हें बाल तत्वों के साथ समन्वय करना चाहिए।