Bird
Raised Fist0
Angularframework~20 mins

ngAfterContentInit for projected content in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Content Projection Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
When is ngAfterContentInit called in Angular?
Consider a component that uses content projection with <ng-content>. When does Angular call the ngAfterContentInit lifecycle hook?
ABefore the projected content is initialized but after the component's view is ready.
BImmediately after the component's constructor runs.
CAfter the component's own view and all projected content have been initialized.
DOnly after the component's view is fully initialized, ignoring projected content.
Attempts:
2 left
💡 Hint
Think about when Angular finishes setting up both the component's template and the content passed inside it.
❓ state_output
intermediate
2:00remaining
What will be logged by ngAfterContentInit?
Given this Angular component and usage, what will the console log inside ngAfterContentInit?
Angular
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core';

@Component({
  selector: 'child-comp',
  template: `<ng-content></ng-content>`
})
export class ChildComp implements AfterContentInit {
  @ContentChild('projected') projectedContent!: ElementRef;

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

// Usage in parent template:
// <child-comp><p #projected>Hello Angular</p></child-comp>
A"<p #projected>Hello Angular</p>"
B"Hello Angular"
CError: Cannot read property 'nativeElement' of undefined
Dundefined
Attempts:
2 left
💡 Hint
The @ContentChild decorator finds the element inside projected content after content init.
📝 Syntax
advanced
2:00remaining
Identify the correct ngAfterContentInit implementation
Which of the following ngAfterContentInit method implementations correctly logs the number of projected items using @ContentChildren?
Angular
import { Component, ContentChildren, QueryList, AfterContentInit, ElementRef } from '@angular/core';

@Component({
  selector: 'list-comp',
  template: `<ng-content></ng-content>`
})
export class ListComp implements AfterContentInit {
  @ContentChildren('item') items!: QueryList<ElementRef>;

  ngAfterContentInit() {
    // ???
  }
}
Aconsole.log(this.items.length);
Bconsole.log(this.items.count);
Cconsole.log(this.items.toArray().length);
Dconsole.log(this.items.size);
Attempts:
2 left
💡 Hint
QueryList has a length property directly to get the number of items.
🔧 Debug
advanced
2:00remaining
Why does @ContentChild return undefined in ngAfterContentInit?
A developer uses @ContentChild('proj') to get a projected element but finds it undefined inside ngAfterContentInit. What is the most likely cause?
Angular
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core';

@Component({
  selector: 'proj-comp',
  template: `<ng-content></ng-content>`
})
export class ProjComp implements AfterContentInit {
  @ContentChild('proj') projElement!: ElementRef;

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

// Usage:
// <proj-comp><div>Content without #proj</div></proj-comp>
AThe projected element does not have the template reference variable #proj.
BngAfterContentInit runs before content projection is done.
CThe component should use @ViewChild instead of @ContentChild.
DThe ElementRef type is incorrect for projected content.
Attempts:
2 left
💡 Hint
Check if the projected element has the exact template reference variable used in @ContentChild.
🧠 Conceptual
expert
3:00remaining
How does Angular handle multiple ngAfterContentInit hooks in nested components with projection?
Consider a parent component projecting content into a child component, which itself projects content into a grandchild component. Which statement best describes the order and behavior of ngAfterContentInit hooks in this nested projection scenario?
AAngular calls <code>ngAfterContentInit</code> only on the top-level component that contains the projection.
BAngular calls <code>ngAfterContentInit</code> from the deepest projected component first, then bubbles up to parents.
CAngular calls <code>ngAfterContentInit</code> on each component only after all projected content in the entire nested tree is initialized.
DAngular calls <code>ngAfterContentInit</code> on each component immediately after its own projected content is initialized, starting from the top-level parent down to the deepest child.
Attempts:
2 left
💡 Hint
Think about how Angular initializes content projection step by step in nested components.

Practice

(1/5)
1. What is the primary purpose of the ngAfterContentInit lifecycle hook in Angular?
easy
A. To run code after projected content has been inserted into the component
B. To initialize component input properties
C. To detect changes in component data bindings
D. To clean up resources before the component is destroyed

Solution

  1. Step 1: Understand the role of ngAfterContentInit

    This hook runs after Angular projects external content into the component's <ng-content> slot.
  2. Step 2: Identify when to use it

    It is used to safely access or manipulate the projected content once it is ready, not before.
  3. Final Answer:

    To run code after projected content has been inserted into the component -> Option A
  4. Quick Check:

    ngAfterContentInit = runs after projected content ready [OK]
Hint: Remember: ngAfterContentInit runs after content projection is done [OK]
Common Mistakes:
  • Confusing ngAfterContentInit with ngOnInit
  • Trying to access projected content before this hook
  • Using it to detect input property changes
2. Which of the following is the correct way to implement ngAfterContentInit in an Angular component?
easy
A. ngAfterContentInit() { console.log('Content initialized'); }
B. ngAfterContentInit: () => { console.log('Content initialized'); }
C. ngAfterContentInit = function() { console.log('Content initialized'); }
D. function ngAfterContentInit() { console.log('Content initialized'); }

Solution

  1. Step 1: Recall Angular lifecycle hook syntax

    Lifecycle hooks are implemented as methods on the component class without assignment or arrow functions.
  2. Step 2: Check each option

    ngAfterContentInit() { console.log('Content initialized'); } uses the correct method syntax. Arrow functions or assignments are not valid lifecycle hook implementations. A standalone function is not a class method.
  3. Final Answer:

    ngAfterContentInit() { console.log('Content initialized'); } -> Option A
  4. Quick Check:

    Lifecycle hooks are class methods, not arrow functions [OK]
Hint: Use method syntax without arrow functions for lifecycle hooks [OK]
Common Mistakes:
  • Using arrow functions for lifecycle hooks
  • Defining lifecycle hooks outside the class
  • Assigning lifecycle hooks to variables
3. Given the following Angular component code, what will be logged to the console when the component is initialized?
import { Component, AfterContentInit, ContentChild, ElementRef } from '@angular/core';

@Component({
  selector: 'child-comp',
  template: ``
})
export class ChildComp implements AfterContentInit {
  @ContentChild('projected') projectedContent!: ElementRef;

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

// Usage in parent template:
// 

Hello World

medium
A. Error: Cannot read property 'nativeElement' of undefined
B. undefined
C. Hello World
D. Empty string

Solution

  1. Step 1: Understand ContentChild and ngAfterContentInit

    The @ContentChild('projected') decorator gets the element with template reference #projected projected inside <ng-content>. This is available after content initialization.
  2. Step 2: Check what ngAfterContentInit logs

    It logs the trimmed text content of the projected element, which is 'Hello World'.
  3. Final Answer:

    Hello World -> Option C
  4. Quick Check:

    ContentChild element text = 'Hello World' [OK]
Hint: ContentChild is ready in ngAfterContentInit, so text logs correctly [OK]
Common Mistakes:
  • Trying to access ContentChild before ngAfterContentInit
  • Forgetting to use template reference variable
  • Assuming projected content is undefined
4. Consider this Angular component code snippet:
import { Component, AfterContentInit, ContentChild, ElementRef } from '@angular/core';

@Component({
  selector: 'proj-comp',
  template: ``
})
export class ProjComp implements AfterContentInit {
  @ContentChild('contentRef') content!: ElementRef;

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

When used as <proj-comp><p>Test</p></proj-comp>, what error will occur and why?
medium
A. Error: ngAfterContentInit is not called
B. Error: content is undefined because no template reference variable 'contentRef' is present
C. No error; logs 'Test' correctly
D. Error: nativeElement is not accessible

Solution

  1. Step 1: Analyze ContentChild selector

    The @ContentChild('contentRef') looks for an element with template reference variable #contentRef inside projected content.
  2. Step 2: Check usage in parent template

    The projected <p>Test</p> has no #contentRef variable, so content is undefined.
  3. Step 3: Understand consequence in ngAfterContentInit

    Accessing this.content.nativeElement causes a runtime error because content is undefined.
  4. Final Answer:

    Error: content is undefined because no template reference variable 'contentRef' is present -> Option B
  5. Quick Check:

    Missing template ref causes undefined ContentChild [OK]
Hint: ContentChild needs matching template ref; else undefined error [OK]
Common Mistakes:
  • Assuming ContentChild finds elements without template refs
  • Ignoring runtime errors from undefined properties
  • Confusing ngAfterContentInit with ngOnInit timing
5. You want to create a component that projects a list of items and highlights the first projected item after content initialization. Which approach correctly uses ngAfterContentInit to achieve this?
import { Component, AfterContentInit, ContentChildren, QueryList, ElementRef } from '@angular/core';

@Component({
  selector: 'highlight-list',
  template: ``
})
export class HighlightList implements AfterContentInit {
  @ContentChildren('item') items!: QueryList<ElementRef>;

  ngAfterContentInit() {
    // What should go here?
  }
}

Options for ngAfterContentInit implementation:
hard
A. document.querySelector('item').style.backgroundColor = 'yellow';
B. this.items.nativeElement.style.backgroundColor = 'yellow';
C. this.items[0].nativeElement.style.backgroundColor = 'yellow';
D. this.items.first.nativeElement.style.backgroundColor = 'yellow';

Solution

  1. Step 1: Understand ContentChildren and QueryList

    @ContentChildren('item') collects all projected elements with template ref #item into a QueryList. Access the first element with items.first.
  2. Step 2: Apply style to first projected item

    Use items.first.nativeElement.style.backgroundColor to highlight the first item safely after content is initialized.
  3. Step 3: Evaluate other options

    this.items.nativeElement.style.backgroundColor = 'yellow'; is invalid because QueryList has no nativeElement property. this.items[0].nativeElement.style.backgroundColor = 'yellow'; is invalid because QueryList is not an array. document.querySelector('item').style.backgroundColor = 'yellow'; uses direct DOM query which breaks Angular encapsulation.
  4. Final Answer:

    this.items.first.nativeElement.style.backgroundColor = 'yellow'; -> Option D
  5. Quick Check:

    Use QueryList.first to access first projected element [OK]
Hint: Use QueryList.first, not array or direct DOM, to access projected items [OK]
Common Mistakes:
  • Treating QueryList as an array
  • Using direct DOM queries instead of Angular references
  • Accessing nativeElement on QueryList itself
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