دونوں child elements/components کے حوالہ جات کے لیے query کرتے ہیں، لیکن وہ مختلف جگہوں پر دیکھتے ہیں: @ViewChild component کے میں query کرتا ہے، جبکہ اس content میں query کرتا ہے جو کے ذریعے component میں ہو۔
دونوں child elements/components کے حوالہ جات کے لیے query کرتے ہیں، لیکن وہ مختلف جگہوں پر دیکھتے ہیں: @ViewChild component کے میں query کرتا ہے، جبکہ اس content میں query کرتا ہے جو کے ذریعے component میں ہو۔
@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 ان elements/components تک رسائی حاصل کرتا ہے جو 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 تک رسائی حاصل کرتا ہے جو parent نے بھیجا ہے (جو <ng-content> کے ذریعے projected ہے) — 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 بمقابلہ ngAfterContentInit) — ضروری ہے جب قابل استعمال components بناتے ہوئے جو اپنے template elements یا اس content کے ساتھ interact کرنے کی ضرورت ہو جو consumers ان میں project کرتے ہوں۔
یہ confusion کا ایک عام نقطہ ہے اور component libraries، tabs، form controls، اور wrappers کی تخلیق میں ایک بار بار آنے والی ضرورت ہے جو child elements کے ساتھ coordinate کرنے کے لیے ضروری ہیں۔