दुवै child elements/components को लागि references को लागि query गर्छन्, तर तिनीहरु फरक फरक ठाउँहरुमा खोज्छन्: @ViewChild component को मा query गर्छ, जबकि component मा गरिएको content को लागि query गर्छ को माध्यमबाट।
दुवै child elements/components को लागि references को लागि query गर्छन्, तर तिनीहरु फरक फरक ठाउँहरुमा खोज्छन्: @ViewChild component को मा query गर्छ, जबकि component मा गरिएको content को लागि query गर्छ को माध्यमबाट।
@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 components/elements को access गर्छ जो component आफैले आफ्नो template मा declare गर्छ — 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 content को access गर्छ जो parent ले पठायो (projected through <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 (projected content) को बीच भिन्नता — र तिनीहरुको सम्मानित lifecycle timings (ngAfterViewInit vs ngAfterContentInit) — reusable components बनाउँदा आवश्यक हुन्छ जो आफ्नो template elements वा content consumers ले project गरेको content सँग interact गर्न चाहन्छन्।
यो confusion को साधारण बिन्दु र component libraries, tabs, form controls, र wrappers को लेखन गर्दा साधारण आवश्यकता हो जो child elements सँग समन्वय गर्न पर्छ।