Bird
Raised Fist0
Angularframework~10 mins

@ContentChild and content projection in Angular - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - @ContentChild and content projection
Parent Component Template
↓
Content Projection Slot <ng-content>
↓
Child Component Receives Projected Content
↓
@ContentChild Decorator Finds Projected Element
↓
Child Component Accesses Projected Content in Code
Content projection inserts external content into a child component's template. @ContentChild lets the child component access that projected content in its code.
Execution Sample
Angular
/* Parent template */
<child-comp>
  <p #proj>Projected Text</p>
</child-comp>

/* Child component */
@ContentChild('proj') projectedParagraph: ElementRef;
Parent projects a paragraph into child. Child uses @ContentChild to get a reference to that paragraph.
Execution Table
StepActionResultComponent StateNotes
1Parent renders <child-comp> with <p #proj> insideChild template includes <ng-content>Parent: content ready; Child: waiting for contentContent is passed to child via <ng-content>
2Angular projects <p #proj> into child's <ng-content>Child template now contains <p> elementChild: projected content insertedContent projection happens here
3Child's @ContentChild('proj') runs after content initprojectedParagraph references <p> elementChild: has reference to projected contentChild can now access projected content in code
4Child accesses projectedParagraph.nativeElement.textContent"Projected Text"Child: can read projected content textShows @ContentChild works
5Parent or child updates projected contentAngular updates DOM accordinglyState updates as neededContent projection is dynamic
6Execution endsAll projected content accessibleStable stateProjection and @ContentChild complete
💡 Content projection completes and @ContentChild references are set after content initialization
Variable Tracker
VariableStartAfter Step 3After Step 4Final
projectedParagraphundefinedElementRef to <p>ElementRef to <p> with text 'Projected Text'ElementRef to <p> with text 'Projected Text'
Key Moments - 3 Insights
Why is projectedParagraph undefined before content initialization?
Because @ContentChild queries run only after Angular projects the content (see execution_table step 3). Before that, the child component has no access to projected elements.
Can the child component access projected content in ngOnInit?
No, @ContentChild is set after ngOnInit, typically in ngAfterContentInit lifecycle hook (refer to step 3 in execution_table). Accessing it earlier returns undefined.
What happens if the parent changes the projected content after initial projection?
Angular updates the DOM and the @ContentChild reference remains valid, reflecting the latest content (see step 5). The child can react to changes using lifecycle hooks.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does @ContentChild get the reference to the projected element?
AStep 3
BStep 2
CStep 4
DStep 1
💡 Hint
Check the 'Action' and 'Result' columns in step 3 where @ContentChild runs after content projection
According to variable_tracker, what is the value of projectedParagraph after step 4?
Aundefined
BElementRef to <p> with text 'Projected Text'
Cnull
DA string 'Projected Text'
💡 Hint
Look at the 'After Step 4' column for projectedParagraph in variable_tracker
If the parent removes the <p #proj> element, what happens to projectedParagraph in the child?
AIt throws an error
BIt remains referencing the old element
CIt becomes undefined or null
DIt updates to a new element automatically
💡 Hint
Consider how Angular updates @ContentChild references when projected content changes (see key_moments about updates)
Concept Snapshot
@ContentChild and content projection:
- Parent projects content into child via <ng-content>
- Child uses @ContentChild('templateRef') to get projected element
- @ContentChild is set after content init (ngAfterContentInit)
- Child can access and manipulate projected content
- Changes in projected content update references dynamically
Full Transcript
This visual trace shows how Angular's content projection works with @ContentChild. The parent component places content inside the child component's tags. Angular projects this content into the child's <ng-content> slot. After projection, Angular runs @ContentChild queries in the child, setting references to the projected elements. The child can then access these elements in its code, for example to read or modify them. The variable tracker shows the projectedParagraph variable starts undefined and becomes a reference to the projected paragraph element after content initialization. Key moments clarify that @ContentChild is only available after content projection completes, typically in ngAfterContentInit. The visual quiz tests understanding of when @ContentChild is set and how it updates if the projected content changes. This helps beginners see the step-by-step flow of content projection and @ContentChild usage in Angular.

Practice

(1/5)
1. What does the Angular decorator @ContentChild do in a component?
easy
A. It projects content from the component into its parent.
B. It creates a new child component inside the template.
C. It gets a reference to a single element inside the projected content.
D. It listens to events emitted by child components.

Solution

  1. Step 1: Understand content projection

    Content projection allows inserting external content inside a component using <ng-content>.
  2. Step 2: Role of @ContentChild

    @ContentChild gets a reference to a single element or directive inside that projected content.
  3. Final Answer:

    It gets a reference to a single element inside the projected content. -> Option C
  4. Quick Check:

    @ContentChild = reference to projected element [OK]
Hint: Remember: @ContentChild targets projected content elements [OK]
Common Mistakes:
  • Confusing @ContentChild with @ViewChild
  • Thinking it creates new elements
  • Assuming it projects content instead of referencing it
2. Which of the following is the correct syntax to use @ContentChild to get a reference to a template variable named myRef?
easy
A. @ContentChild('myRef') myElement!: ElementRef;
B. @ContentChild(myRef) myElement!: ElementRef;
C. @ContentChild(#myRef) myElement!: ElementRef;
D. @ContentChild(myRef, {static: true}) myElement!: ElementRef;

Solution

  1. Step 1: Correct syntax for @ContentChild selector

    The selector must be a string matching the template variable name, so it should be quoted: 'myRef'.
  2. Step 2: Static option usage

    Static option is optional and usually false by default; not required here.
  3. Final Answer:

    @ContentChild('myRef') myElement!: ElementRef; -> Option A
  4. Quick Check:

    Use quotes around template variable name in @ContentChild [OK]
Hint: Use quotes around template variable name in @ContentChild [OK]
Common Mistakes:
  • Omitting quotes around the selector string
  • Using # inside the selector string
  • Confusing static option necessity
3. Given this component code:
@Component({ selector: 'child-comp', template: `` })
export class ChildComp {
  @ContentChild('proj') projElement!: ElementRef;

  ngAfterContentInit() {
    console.log(this.projElement.nativeElement.textContent);
  }
}

And usage:

Hello World


What will be logged to the console?
medium
A. Hello World
B. undefined
C. Error: projElement is undefined
D. Empty string

Solution

  1. Step 1: Understand content projection and @ContentChild

    The <p #proj> is projected inside <ng-content>. @ContentChild('proj') gets its reference.
  2. Step 2: ngAfterContentInit timing

    ngAfterContentInit runs after projected content is initialized, so projElement is defined and accessible.
  3. Final Answer:

    Hello World -> Option A
  4. Quick Check:

    Projected element text logged correctly [OK]
Hint: Use ngAfterContentInit to access projected content safely [OK]
Common Mistakes:
  • Trying to access projElement before ngAfterContentInit
  • Assuming @ContentChild does not find projected elements
  • Confusing @ViewChild with @ContentChild
4. Consider this component code:
@Component({ selector: 'proj-comp', template: `` })
export class ProjComp {
  @ContentChild('item') itemRef!: ElementRef;

  ngOnInit() {
    console.log(this.itemRef.nativeElement.textContent);
  }
}

And usage:
Test

What problem will occur when running this code?
medium
A. Logs 'Test' correctly
B. Error because itemRef is undefined in ngOnInit
C. Syntax error due to missing decorator
D. Logs empty string

Solution

  1. Step 1: Lifecycle hook timing for @ContentChild

    @ContentChild references are not available in ngOnInit; they become available in ngAfterContentInit.
  2. Step 2: Accessing itemRef in ngOnInit

    Accessing itemRef in ngOnInit causes it to be undefined, leading to runtime error when accessing nativeElement.
  3. Final Answer:

    Error because itemRef is undefined in ngOnInit -> Option B
  4. Quick Check:

    Use ngAfterContentInit for @ContentChild access [OK]
Hint: Access @ContentChild only in ngAfterContentInit [OK]
Common Mistakes:
  • Accessing @ContentChild in ngOnInit
  • Assuming @ContentChild is available immediately
  • Ignoring lifecycle hook order
5. You want to create a component that projects multiple paragraphs and highlights the first paragraph. Which approach correctly achieves this?

Options:
A) Use @ContentChildren('para') and highlight the first in the list.
B) Use @ContentChild('para') and add #para to the first paragraph only.
C) Use @ViewChild('para') inside the component template.
D) Use @ContentChild without a selector and highlight all paragraphs.
hard
A. Use @ContentChild without a selector and highlight all paragraphs.
B. Use @ContentChild('para') and add #para to the first paragraph only.
C. Use @ViewChild('para') inside the component template.
D. Use @ContentChildren('para') and highlight the first in the list.

Solution

  1. Step 1: Understand multiple projected elements

    When projecting multiple elements with the same template variable, use @ContentChildren to get all references.
  2. Step 2: Highlight the first paragraph

    @ContentChildren returns a QueryList; you can access the first element and apply highlight logic.
  3. Final Answer:

    Use @ContentChildren('para') and highlight the first in the list. -> Option D
  4. Quick Check:

    Multiple projected elements need @ContentChildren [OK]
Hint: Use @ContentChildren for multiple projected elements [OK]
Common Mistakes:
  • Using @ContentChild for multiple elements
  • Using @ViewChild for projected content
  • Omitting selector in @ContentChild
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard