Bird
0
0

Given the following Angular component code, what will be logged to the console when the component is initialized?

medium📝 component behavior Q13 of 15
Angular - Lifecycle Hooks
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

AError: Cannot read property 'nativeElement' of undefined
Bundefined
CHello World
DEmpty string
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes