दोन्ही बाल घटकांवर संदर्भ शोधतात, परंतु भिन्न ठिकाणी पाहतात: @ViewChild घटकाच्या स्वतःच्या template ला प्रश्न करतो, तर @ContentChild द्वारे घटकात सामग्री प्रश्न करतो.
दोन्ही बाल घटकांवर संदर्भ शोधतात, परंतु भिन्न ठिकाणी पाहतात: @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 (प्रोजेक्ट केलेली सामग्री) मध्ये फरक करणे — आणि त्यांच्या संबंधित जीवनचक्र वेळ (ngAfterViewInit vs ngAfterContentInit) — पुनः वापरण्यायोग्य घटक तयार करताना आवश्यक आहे जे त्यांच्या स्वतःच्या template घटकांशी किंवा उपभोक्ते घटकात प्रोजेक्ट केलेली सामग्रीशी परस्पर क्रिया करतात.
हे घटक लायब्ररी, टॅब्स, फॉर्म नियंत्रण आणि रॅपर तयार करताना भ्रमणा मुद्दा आणि वारंवार आवश्यकता आहे जे बाल घटकांशी समन्वय करतात.