இரண்டும் சார்பு உறுப்புகள்/கூறுகளுக்கான குறிப்புகளைத் தேடுகின்றன, ஆனால் அவை வெவ்வேறு இடங்களில் தேடுகின்றன: @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) — மீண்டும் பயன்படுத்தக்கூடிய கூறுகளை உருவாக்கும்போது அவசியமாகும், அவை தங்கள் சொந்த வார்ப்பு உறுப்புகள் அல்லது நுகர்வோர் கூறுக்குள் திட்டமிடும் உள்ளடக்கத்துடன் ஆற்றல்படுத்த வேண்டும்.
இது ஒரு பொதுவான குழப்பத்தின் புள்ளி மற்றும் கூறு நூலகங்கள், தாბுகள், படிவக் கட்டுப்பாடுகள் மற்றும் பொருத்தமாகக் கூட்டிணைக்க வேண்டிய சுற்றுப்புறம் ஆழிக்க ஒரு பொதுவான தேவை.