Bird
0
0

Identify the error in the following Angular component code using @ViewChild:

medium📝 Debug Q14 of 15
Angular - Component Interaction
Identify the error in the following Angular component code using @ViewChild:
  export class MyComponent {
    @ViewChild('myButton') buttonRef: ElementRef;

    ngOnInit() {
      this.buttonRef.nativeElement.click();
    }
  }
AAccessing @ViewChild reference before view initialization
BMissing quotes around 'myButton' in @ViewChild
CUsing ElementRef instead of TemplateRef
DNo error, code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Check lifecycle hook used

    ngOnInit runs before the view is fully initialized, so @ViewChild references are not ready yet.
  2. Step 2: Correct lifecycle hook for @ViewChild access

    Accessing @ViewChild should be done in ngAfterViewInit to ensure the element exists.
  3. Final Answer:

    Accessing @ViewChild reference before view initialization -> Option A
  4. Quick Check:

    @ViewChild ready only after ngAfterViewInit [OK]
Quick Trick: Use ngAfterViewInit, not ngOnInit, to access @ViewChild [OK]
Common Mistakes:
  • Accessing @ViewChild in ngOnInit causing undefined errors
  • Confusing lifecycle hooks for view queries
  • Ignoring the timing of template element availability

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes