Bird
Raised Fist0
Angularframework~20 mins

@ViewChild decorator usage in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Angular @ViewChild Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What will be the output of this Angular component using @ViewChild?

Consider this Angular component code snippet:

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-sample',
  template: `<input #inputRef type='text' value='Hello' />` 
})
export class SampleComponent implements AfterViewInit {
  @ViewChild('inputRef') inputElement!: ElementRef;

  ngAfterViewInit() {
    console.log(this.inputElement.nativeElement.value);
  }
}

What will be logged to the console when this component renders?

Angular
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-sample',
  template: `<input #inputRef type='text' value='Hello' />` 
})
export class SampleComponent implements AfterViewInit {
  @ViewChild('inputRef') inputElement!: ElementRef<HTMLInputElement>;

  ngAfterViewInit() {
    console.log(this.inputElement.nativeElement.value);
  }
}
Aundefined
Bnull
C"Hello"
DError: inputElement is undefined
Attempts:
2 left
💡 Hint

Remember when @ViewChild references are available in the component lifecycle.

📝 Syntax
intermediate
2:00remaining
Which @ViewChild syntax correctly queries a component by its class type?

Given a child component named ChildComponent, which @ViewChild declaration correctly gets its instance?

Angular
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  template: `<child-component></child-component>`
})
export class ParentComponent {
  // Which @ViewChild is correct?
}
A@ViewChild('ChildComponent') child!: ChildComponent;
B@ViewChild(ChildComponent) child!: ChildComponent;
C@ViewChild() child!: ChildComponent;
D@ViewChild('child') child!: ChildComponent;
Attempts:
2 left
💡 Hint

When querying by component class, you pass the class itself, not a string.

❓ lifecycle
advanced
2:00remaining
When is the @ViewChild reference available in the component lifecycle?

In which lifecycle hook is the @ViewChild property guaranteed to be initialized and safe to use?

AngAfterViewInit()
BngOnInit()
Cconstructor()
DngAfterContentInit()
Attempts:
2 left
💡 Hint

Think about when the component's view is fully rendered.

🔧 Debug
advanced
2:00remaining
Why does this @ViewChild usage cause an error?

Examine this Angular component code:

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-debug',
  template: `
Content
` }) export class DebugComponent { @ViewChild('myDiv') myDiv!: ElementRef; ngOnInit() { console.log(this.myDiv.nativeElement.textContent); } }

What error will occur and why?

Angular
import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-debug',
  template: `<div #myDiv>Content</div>`
})
export class DebugComponent {
  @ViewChild('myDiv') myDiv!: ElementRef;

  ngOnInit() {
    console.log(this.myDiv.nativeElement.textContent);
  }
}
ANo output, silent failure
BLogs 'Content' correctly
CSyntaxError due to missing semicolon
DError: Cannot read property 'nativeElement' of undefined
Attempts:
2 left
💡 Hint

Consider when @ViewChild properties are initialized relative to lifecycle hooks.

❓ state_output
expert
2:30remaining
What is the final value of the input after this interaction with @ViewChild?

Given this Angular component:

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-expert',
  template: `` 
})
export class ExpertComponent implements AfterViewInit {
  @ViewChild('inputRef') inputElement!: ElementRef;

  ngAfterViewInit() {
    this.inputElement.nativeElement.value = 'Changed';
  }

  changeValue() {
    this.inputElement.nativeElement.value = 'Clicked';
  }
}

If the user clicks a button that calls changeValue() after the view loads, what is the input's value?

Angular
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-expert',
  template: `<input #inputRef type='text' value='Start' />` 
})
export class ExpertComponent implements AfterViewInit {
  @ViewChild('inputRef') inputElement!: ElementRef<HTMLInputElement>;

  ngAfterViewInit() {
    this.inputElement.nativeElement.value = 'Changed';
  }

  changeValue() {
    this.inputElement.nativeElement.value = 'Clicked';
  }
}
A"Clicked"
B"Changed"
C"Start"
Dundefined
Attempts:
2 left
💡 Hint

Think about the order of operations: initial value, lifecycle hook, and user interaction.

Practice

(1/5)
1. What is the primary purpose of the @ViewChild decorator in Angular?
easy
A. To get a reference to a template element or child component
B. To create a new Angular module
C. To define routes in the application
D. To style components dynamically

Solution

  1. Step 1: Understand the role of @ViewChild

    @ViewChild is used to access a child element or component from the template directly in the class.
  2. Step 2: Compare with other options

    Creating modules, defining routes, or styling are unrelated to @ViewChild's purpose.
  3. Final Answer:

    To get a reference to a template element or child component -> Option A
  4. Quick Check:

    @ViewChild = Reference to template element [OK]
Hint: Remember: @ViewChild grabs template elements or child components [OK]
Common Mistakes:
  • Confusing @ViewChild with routing or module decorators
  • Thinking @ViewChild creates components
  • Assuming @ViewChild styles elements
2. Which of the following is the correct syntax to use @ViewChild to get a reference to a template element with template variable #myInput?
easy
A. @ViewChild(myInput) inputElement: ElementRef;
B. @ViewChild('myInput') inputElement: ElementRef;
C. @ViewChild(#myInput) inputElement: ElementRef;
D. @ViewChild('inputElement') myInput: ElementRef;

Solution

  1. Step 1: Check correct string usage in @ViewChild

    The template variable name must be passed as a string, so it should be '@ViewChild('myInput')'.
  2. Step 2: Validate variable names and types

    The variable name in the class can be anything, here 'inputElement', and type should be ElementRef for native elements.
  3. Final Answer:

    @ViewChild('myInput') inputElement: ElementRef; -> Option B
  4. Quick Check:

    Template variable name as string in @ViewChild [OK]
Hint: Always pass template variable name as a string in @ViewChild [OK]
Common Mistakes:
  • Omitting quotes around template variable name
  • Using # inside @ViewChild argument
  • Swapping variable names and template references
3. Given the following Angular component code, what will be logged to the console after the view initializes?
  <input #myInput type="text" value="Hello">

  export class MyComponent implements AfterViewInit {
    @ViewChild('myInput') inputRef!: ElementRef<HTMLInputElement>;

    ngAfterViewInit() {
      console.log(this.inputRef.nativeElement.value);
    }
  }
medium
A. undefined
B. Error: inputRef is undefined
C. null
D. Hello

Solution

  1. Step 1: Understand @ViewChild and ngAfterViewInit timing

    @ViewChild gets the input element reference, and ngAfterViewInit runs after the view is ready, so inputRef is defined.
  2. Step 2: Access nativeElement value

    inputRef.nativeElement.value accesses the input's value attribute, which is 'Hello'.
  3. Final Answer:

    Hello -> Option D
  4. Quick Check:

    Access input value via @ViewChild after view init [OK]
Hint: Access @ViewChild only after ngAfterViewInit to get values [OK]
Common Mistakes:
  • Trying to access @ViewChild in constructor or ngOnInit
  • Assuming inputRef is null or undefined after view init
  • Confusing nativeElement with the ElementRef itself
4. Identify the error in the following Angular component code using @ViewChild:
  export class MyComponent {
    @ViewChild('myButton') buttonRef: ElementRef;

    ngOnInit() {
      this.buttonRef.nativeElement.click();
    }
  }
medium
A. Accessing @ViewChild reference before view initialization
B. Missing quotes around 'myButton' in @ViewChild
C. Using ElementRef instead of TemplateRef
D. No error, code is correct

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]
Hint: 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
5. You want to call a method focusInput() on a child component ChildComponent using @ViewChild. Which of the following is the correct way to do this safely after the view initializes?
hard
A. Use @ViewChild(ChildComponent) child: ElementRef; and call this.child.nativeElement.focusInput() inside ngAfterViewInit()
B. Use @ViewChild('child') child: ChildComponent; and call this.child.focusInput() inside constructor()
C. Use @ViewChild(ChildComponent) child!: ChildComponent; and call this.child.focusInput() inside ngAfterViewInit()
D. Use @ViewChild('child') child: ElementRef; and call this.child.focusInput() inside ngOnInit()

Solution

  1. Step 1: Correct @ViewChild usage for child component

    Use the component class type in @ViewChild to get the child component instance, e.g. @ViewChild(ChildComponent).
  2. Step 2: Call child method after view initialization

    Call the method inside ngAfterViewInit to ensure the child component is ready.
  3. Final Answer:

    Use @ViewChild(ChildComponent) child!: ChildComponent; and call this.child.focusInput() inside ngAfterViewInit() -> Option C
  4. Quick Check:

    Child component method call via @ViewChild after view init [OK]
Hint: Use component class in @ViewChild and call methods after ngAfterViewInit [OK]
Common Mistakes:
  • Calling child methods in constructor or ngOnInit
  • Using ElementRef instead of component class for child components
  • Trying to access nativeElement for component methods
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard