Bird
Raised Fist0
Angularframework~10 mins

@ContentChild and content projection in Angular - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to select the projected content using @ContentChild.

Angular
import { Component, ContentChild, AfterContentInit } from '@angular/core';

@Component({
  selector: 'child-comp',
  template: '<p>Projected content: {{contentText}}</p>'
})
export class ChildComponent implements AfterContentInit {
  @ContentChild('projContent') [1];
  contentText = '';

  ngAfterContentInit() {
    this.contentText = this.projContent.nativeElement.textContent.trim();
  }
}
Drag options to blanks, or click blank then click option'
AprojContent
BcontentRef
CcontentChild
Dprojected
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name that does not match the template reference variable.
Forgetting to use @ContentChild decorator.
2fill in blank
medium

Complete the code to project content inside the child component's template.

Angular
<child-comp>
  <div [1]="projContent">Hello from parent!</div>
</child-comp>
Drag options to blanks, or click blank then click option'
A*
B#
C@
D$
Attempts:
3 left
💡 Hint
Common Mistakes
Using '*' which is for structural directives.
Using '@' or '$' which are invalid in this context.
3fill in blank
hard

Fix the error in the child component to correctly access the projected content's native element.

Angular
import { Component, ContentChild, ElementRef, AfterContentInit } from '@angular/core';

@Component({
  selector: 'child-comp',
  template: '<p>Content: {{contentText}}</p>'
})
export class ChildComponent implements AfterContentInit {
  @ContentChild('projContent') projContent: [1];
  contentText = '';

  ngAfterContentInit() {
    this.contentText = this.projContent.nativeElement.textContent.trim();
  }
}
Drag options to blanks, or click blank then click option'
ARenderer2
BTemplateRef
CViewChild
DElementRef
Attempts:
3 left
💡 Hint
Common Mistakes
Using TemplateRef which does not have nativeElement.
Using ViewChild instead of ContentChild.
4fill in blank
hard

Fill both blanks to correctly define and use @ContentChild with a selector.

Angular
import { Component, ContentChild, ElementRef, AfterContentInit } from '@angular/core';

@Component({
  selector: 'child-comp',
  template: '<div>Projected: {{text}}</div>'
})
export class ChildComponent implements AfterContentInit {
  @ContentChild([1]) content: ElementRef;
  text = '';

  ngAfterContentInit() {
    this.text = this.content?.nativeElement?.[2].trim();
  }
}
Drag options to blanks, or click blank then click option'
A'p'
BtextContent
CinnerHTML
D'div'
Attempts:
3 left
💡 Hint
Common Mistakes
Using innerHTML which returns HTML, not plain text.
Using a wrong selector that does not match projected content.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps projected elements' tag names to their trimmed text content.

Angular
import { Component, ContentChildren, QueryList, AfterContentInit, ElementRef } from '@angular/core';

@Component({
  selector: 'child-comp',
  template: '<ng-content></ng-content>'
})
export class ChildComponent implements AfterContentInit {
  @ContentChildren([1]) elements!: QueryList<ElementRef>;
  contentMap: Record<string, string> = {};

  ngAfterContentInit() {
    this.contentMap = this.elements.reduce((acc, el) => {
      acc[el.nativeElement.tagName.toLowerCase()] = el.nativeElement.[2].[3]();
      return acc;
    }, {} as Record<string, string>);
  }
}
Drag options to blanks, or click blank then click option'
AElementRef
BtextContent
Ctrim
DTemplateRef
Attempts:
3 left
💡 Hint
Common Mistakes
Using TemplateRef instead of ElementRef.
Forgetting to call trim() to remove extra spaces.

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