બંને બાળ તત્વો/ઘટકોના સંદર્ભો માટે પ્રશ્ન કરે છે, પરંતુ તેઓ વિવિધ સ્થાનો પર જોવે છે: @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 ટાઈમિંગ (ngAfterViewInit vs ngAfterContentInit) — પુનઃવપરાશ્રય ઘટકો બાંધતી વખતે આવશ્યક છે જે તેમના પોતાના template તત્વો અથવા ગ્રાહકો તેમમાં પ્રજેક્ટ કરતી સામગ્રી સાથે ક્રિયાપ્રતિક્રિયા કરવાની જરૂર છે.
તે ગોંધળની સામાન્ય બાબત છે અને ઘટક પુસ્તકાલયો, tabs, ફોર્મ નિયંત્રણો અને wrapper બાંધતી વખતે વારંવાર જરૂર છે જે બાળ તત્વો સાથે સમન્વય કરવું આવશ્યક છે.