Bird
0
0

What is wrong with this code snippet?

medium📝 Debug Q6 of 15
Angular - Component Interaction
What is wrong with this code snippet?
  @ViewChild('myDiv') myDiv: ElementRef;

  ngOnInit() {
    console.log(this.myDiv.nativeElement.innerText);
  }
AThe template variable name should not be a string
BMissing import for ElementRef
CAccessing @ViewChild in ngOnInit is too early; it is undefined
DThe property should be private
Step-by-Step Solution
Solution:
  1. Step 1: Understand lifecycle timing for @ViewChild

    @ViewChild references are set after the view initializes, so ngOnInit is too early to access them.
  2. Step 2: Correct lifecycle hook to use

    ngAfterViewInit is the correct place to access @ViewChild properties safely.
  3. Final Answer:

    Accessing @ViewChild in ngOnInit is too early; it is undefined -> Option C
  4. Quick Check:

    Use ngAfterViewInit to access @ViewChild [OK]
Quick Trick: Access @ViewChild only after view initialization (ngAfterViewInit) [OK]
Common Mistakes:
  • Accessing @ViewChild in ngOnInit or constructor
  • Confusing lifecycle hooks
  • Ignoring undefined errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes