Zarówno jak i wyszukują referencje do elementów/komponentów podrzędnych, ale patrzą na : wyszukuje w komponentu, podczas gdy wyszukuje zawartość komponentu za pośrednictwem .
Zarówno jak i wyszukują referencje do elementów/komponentów podrzędnych, ale patrzą na : wyszukuje w komponentu, podczas gdy wyszukuje zawartość komponentu za pośrednictwem .
@ViewChild@ContentChild@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 uzyskuje dostęp do elementów/komponentów, które komponent sam deklaruje w swoim szablonie — dostępne w 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 uzyskuje dostęp do zawartości, którą rodzic przekazał (rzutowanej przez <ng-content>) — dostępne w 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)
Rozdystyngowanie między @ViewChild (Twój szablon) a @ContentChild (rzutowana zawartość) — oraz ich odpowiednich czasów cyklu życia (ngAfterViewInit vs ngAfterContentInit) — jest niezbędne podczas budowania komponentów wielokrotnego użytku, które muszą współdziałać z ich własnymi elementami szablonu lub zawartością, którą konsumenci do nich rzutują.
To jest częsty punkt zamieszania i częsta potrzeba podczas pisania bibliotek komponentów, kart, kontrolek formularzy i opakowań, które muszą koordynować się z elementami podrzędnymi.
@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)