రెండూ చైల్డ్ ఎలిమెంట్ల/కంపోనెంట్ల కోసం సూచనలను చేసుకుంటాయి, కానీ అవి వేర్వేరు ప్రదేశాలలో చూస్తాయి: @ViewChild కంపోనెంట్ యొక్క చేస్తుంది, అయితే ద్వారా కంపోనెంట్లో విషయవస్తువును చేస్తుంది.
రెండూ చైల్డ్ ఎలిమెంట్ల/కంపోనెంట్ల కోసం సూచనలను చేసుకుంటాయి, కానీ అవి వేర్వేరు ప్రదేశాలలో చూస్తాయి: @ViewChild కంపోనెంట్ యొక్క చేస్తుంది, అయితే ద్వారా కంపోనెంట్లో విషయవస్తువును చేస్తుంది.
@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 కంపోనెంట్ దాని టెంప్లేట్లో ఘోషిస్తున్న ఎలిమెంట్లు/కంపోనెంట్లను యాక్సెస్ చేస్తుంది — **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 (మీ టెంప్లేట్) నుండి @ContentChild (ప్రోజెక్ట్ చేయబడిన విషయవస్తువు)ను వేరుచేయడం — మరియు వాటి సంబంధిత జీవిత చక్ర సమయాలను (ngAfterViewInit vs ngAfterContentInit) — పునర్వినియోగ్యమైన కంపోనెంట్లను నిర్మించేటప్పుడు అవసరమైనది, ఇవి వాటి స్వంత టెంప్లేట్ ఎలిమెంట్లు లేదా వినియోగదారులు కంపోనెంట్లోకి ప్రోజెక్ట్ చేసే విషయవస్తువుతో సంకర్షణ చేయాలి.
ఇది ఒక సాధారణ గందరగోళ బిందువు మరియు కంపోనెంట్ లైబ్రరీలు, ట్యాబ్లు, ఫారమ్ కంట్రోల్లు మరియు చైల్డ్ ఎలిమెంట్లతో సమన్వయం చేయవలసిన래పర్ల రచన చేసేటప్పుడు సాధారణ అవసరం.