Bird
0
0

Which of the following is a correct way to use @ViewChild to get a reference to a template variable named myDiv?

easy📝 Conceptual Q2 of 15
Angular - Component Interaction
Which of the following is a correct way to use @ViewChild to get a reference to a template variable named myDiv?
A@ViewChild(myDiv) myDivRef: ElementRef;
B@ViewChild('myDivRef') myDiv: ElementRef;
C@ViewChild('#myDiv') myDivRef: ElementRef;
D@ViewChild('myDiv') myDivRef: ElementRef;
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct syntax for template variable

    Template variables are referenced as strings without the '#' symbol inside @ViewChild, so '@ViewChild('myDiv')' is correct.
  2. Step 2: Check variable names and types

    The variable name in the class can be anything, but it should match the decorator usage. @ViewChild('myDiv') myDivRef: ElementRef; correctly uses 'myDivRef' for the ElementRef.
  3. Final Answer:

    @ViewChild('myDiv') myDivRef: ElementRef; -> Option D
  4. Quick Check:

    Template variable reference = '@ViewChild('myDiv')' [OK]
Quick Trick: Use string name without '#' inside @ViewChild to reference template vars [OK]
Common Mistakes:
  • Including '#' in the string inside @ViewChild
  • Using variable names inconsistently
  • Omitting quotes around the template variable name

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes