Bird
0
0

Why is ngAfterViewInit preferred over ngOnInit for DOM manipulation in Angular components?

hard📝 Conceptual Q10 of 15
Angular - Lifecycle Hooks
Why is ngAfterViewInit preferred over ngOnInit for DOM manipulation in Angular components?
ABecause ngAfterViewInit runs before the component is created
BBecause the component's view and child views are fully initialized only after ngAfterViewInit runs
CBecause ngOnInit runs multiple times causing performance issues
DBecause ngOnInit cannot access component properties
Step-by-Step Solution
Solution:
  1. Step 1: Compare ngOnInit and ngAfterViewInit timing

    ngOnInit runs before the view is fully rendered, so DOM elements may not exist yet.
  2. Step 2: Understand why DOM manipulation needs view ready

    ngAfterViewInit runs after the view and child views are initialized, ensuring DOM elements are accessible.
  3. Final Answer:

    Because the component's view and child views are fully initialized only after ngAfterViewInit runs -> Option B
  4. Quick Check:

    DOM manipulation requires view ready after ngAfterViewInit [OK]
Quick Trick: Manipulate DOM only after ngAfterViewInit runs [OK]
Common Mistakes:
  • Thinking ngOnInit runs multiple times
  • Believing ngAfterViewInit runs before creation
  • Assuming ngOnInit cannot access properties

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes