Angular › Template Reference Variables & ViewChild

What is the difference between ViewChild and ContentChild in Angular?

Beginner

Answer

ViewChild accesses an element or component that is part of a component's own template, defined directly by that component. ContentChild accesses an element or component that was projected into the component from outside, using content projection, meaning it comes from whatever content the parent using the component actually supplied.
// ViewChild, accesses something defined in this component's own template
@ViewChild('internalElement') internal!: ElementRef;

// ContentChild, accesses something projected in from outside via ng-content
@ContentChild('projectedElement') projected!: ElementRef;
Real-world example A custom card component uses ViewChild to reference its own internal header element, while using ContentChild to reference a specific piece of content that a parent using the card component chose to project inside it.

Common follow-ups: In which lifecycle hook does ContentChild data become reliably available?;Can a component use both ViewChild and ContentChild together for different purposes?