Bird
0
0

Why does this Angular component throw an error?

medium📝 Debug Q7 of 15
Angular - Lifecycle Hooks
Why does this Angular component throw an error?
export class SampleComponent implements AfterContentInit {
  @ContentChild('proj') proj!: ElementRef;
  ngAfterContentInit() {
    console.log(this.proj.nativeElement.textContent);
  }
}

Component template: <div #proj>Hi</div>

But the error is: Cannot read property 'nativeElement' of undefined

AThe projected element is inside the component's own template, not projected content
BThe #proj reference is misspelled
CElementRef is not imported
DngAfterContentInit is called too early
Step-by-Step Solution
Solution:
  1. Step 1: Understand content projection

    @ContentChild only finds elements projected from outside, not inside the component's own template.
  2. Step 2: Analyze template

    The #proj element is inside the component's own template, so @ContentChild('proj') does not find it, proj is undefined and accessing nativeElement causes error.
  3. Final Answer:

    The projected element is inside the component's own template, not projected content -> Option A
  4. Quick Check:

    @ContentChild targets projected content only [OK]
Quick Trick: Use @ViewChild for own template elements, @ContentChild for projected [OK]
Common Mistakes:
  • Using @ContentChild for own template elements
  • Assuming #proj is found regardless of projection
  • Ignoring lifecycle timing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes