Bird
0
0

Consider this Angular component code snippet:

medium📝 Debug Q14 of 15
Angular - Lifecycle Hooks
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?
AError: ngAfterContentInit is not called
BError: content is undefined because no template reference variable 'contentRef' is present
CNo error; logs 'Test' correctly
DError: nativeElement is not accessible
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes