ਦੋਵੇਂ child elements/components ਲਈ references ਲਈ query ਕਰਦੇ ਹਨ, ਪਰ ਉਹ ਵੱਖ-ਵੱਖ ਥਾਂਵਾਂ ਤੇ ਨਜ਼ਰ ਰੱਖਦੇ ਹਨ: @ViewChild component ਦੇ ਤੋਂ query ਕਰਦਾ ਹੈ, ਜਦਕਿ content ਲਈ query ਕਰਦਾ ਹੈ ਜੋ component ਵਿਚ ਦੁਆਰਾ ਕੀਤੀ ਗਈ ਹੈ।
ਦੋਵੇਂ child elements/components ਲਈ references ਲਈ 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 ਨੇ ਭੇਜੀ (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 ਨਾਲ coordinate ਕਰਨਾ ਹੋਵੇ।