Bird
0
0

Why does this Angular component fail to log the child element's text content in ngAfterViewInit?

medium📝 Debug Q7 of 15
Angular - Lifecycle Hooks
Why does this Angular component fail to log the child element's text content in ngAfterViewInit?
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';

@Component({ selector: 'app-demo', template: `

Sample

` }) export class DemoComponent implements AfterViewInit { @ViewChild('para') para!: ElementRef; ngAfterViewInit() { console.log(this.para.nativeElement.textContent); } }
AThe code is correct and will log 'Sample'
BThe para property is not initialized before ngAfterViewInit
CThe para property should be accessed in ngOnInit
DThe @ViewChild decorator is missing { static: false } option
Step-by-Step Solution
Solution:
  1. Step 1: Understand @ViewChild timing

    By default, @ViewChild with static: false initializes after view init.
  2. Step 2: Confirm access in ngAfterViewInit

    Accessing para.nativeElement.textContent in ngAfterViewInit is correct and logs 'Sample'.
  3. Final Answer:

    The code is correct and will log 'Sample' -> Option A
  4. Quick Check:

    @ViewChild works in ngAfterViewInit by default [OK]
Quick Trick: Access @ViewChild elements in ngAfterViewInit for safety [OK]
Common Mistakes:
  • Assuming static: false must be set explicitly
  • Trying to access @ViewChild in ngOnInit
  • Thinking para is undefined in ngAfterViewInit

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes