Oboje pretražuju reference na podređene elemente/komponente, ali gledaju na različitim mjestima: @ViewChild pretražuje vlastivi template komponente, dok pretražuje sadržaj komponentu kroz .
Oboje pretražuju reference na podređene elemente/komponente, ali gledaju na različitim mjestima: @ViewChild pretražuje vlastivi template komponente, dok pretražuje sadržaj komponentu kroz .
@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 pristupa elementima/komponentama koje sama komponenta deklarira u svom template-u — dostupno u 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 pristupa sadržaju koji je roditelj prosljeđivao (projiciran kroz <ng-content>) — dostupno u 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)
Razlikovanje @ViewChild (vaš template) od @ContentChild (projicirani sadržaj) — i njihovim odgovarajućim vremenima životnog ciklusa (ngAfterViewInit vs ngAfterContentInit) — essencijalno je pri izgradnji ponovno iskoristivih komponenti koje trebaju stupiti u interakciju sa bilo vlastitim template elementima ili sadržajem koji konzumenti projiciraju u njih.
To je česta točka zbunjenosti i česta potreba pri izradi biblioteka komponenti, tabova, kontrola obrazaca i wrappera koji se moraju koordinirati s podređenim elementima.