Bird
0
0

What is wrong with this code snippet inside a component?

medium📝 Debug Q6 of 15
Angular - Component Interaction
What is wrong with this code snippet inside a component?
@ContentChild('proj') projElem: ElementRef;
ngOnInit() { console.log(this.projElem.nativeElement); }
AMissing @ViewChild decorator instead of @ContentChild
BAccessing @ContentChild in ngOnInit may cause undefined error
CprojElem should be a TemplateRef, not ElementRef
DThe selector string 'proj' should be a type, not string
Step-by-Step Solution
Solution:
  1. Step 1: Timing of @ContentChild availability

    @ContentChild references are not set before ngAfterContentInit.
  2. Step 2: Accessing in ngOnInit causes error

    Accessing projElem.nativeElement in ngOnInit risks undefined because content is not initialized yet.
  3. Final Answer:

    Accessing @ContentChild in ngOnInit may cause undefined error -> Option B
  4. Quick Check:

    Access @ContentChild after ngAfterContentInit [OK]
Quick Trick: Never access @ContentChild before ngAfterContentInit [OK]
Common Mistakes:
  • Accessing @ContentChild in ngOnInit
  • Confusing @ContentChild with @ViewChild
  • Wrong type for projected element

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes