Bird
Raised Fist0
Angularframework~10 mins

ngAfterViewInit for view ready in Angular - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - ngAfterViewInit for view ready
Component Initialized
↓
ngOnInit runs
↓
Template Rendered
↓
ngAfterViewInit runs
↓
View is Ready for DOM Access
↓
Perform DOM or Child Component Actions
Shows the lifecycle flow where ngAfterViewInit runs after the component's view is fully rendered and ready.
Execution Sample
Angular
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';

@Component({ selector: 'app-sample', template: '<div #box>Box</div>' })
export class SampleComponent implements AfterViewInit {
  @ViewChild('box') box!: ElementRef;
  ngAfterViewInit() {
    console.log(this.box.nativeElement.textContent);
  }
}
Logs the text content of a div after the view is fully initialized.
Execution Table
StepLifecycle HookView StatusActionOutput
1ConstructorView not renderedComponent instance createdNo output
2ngOnInitView not renderedInitialize dataNo output
3Template RenderView renderedDOM elements createdNo output
4ngAfterViewInitView fully renderedAccess @ViewChild elementLogs 'Box' text content
5Component ReadyView readyFurther DOM or child component actionsNo output
💡 ngAfterViewInit runs after the view is fully rendered, allowing safe DOM access.
Variable Tracker
VariableConstructorngOnInitAfterViewInitFinal
boxundefinedundefinedElementRef to <div>ElementRef to <div>
Key Moments - 2 Insights
Why can't we access the @ViewChild element in ngOnInit?
Because the view is not yet rendered during ngOnInit, so @ViewChild elements are still undefined. See execution_table step 2 and 3.
What guarantees that the DOM element is ready in ngAfterViewInit?
Angular calls ngAfterViewInit only after the template and child views are fully initialized and rendered, as shown in execution_table step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the status of the view during ngOnInit?
AView fully rendered
BView not rendered
CView partially rendered
DView destroyed
💡 Hint
Check the 'View Status' column at step 2 in the execution_table.
At which step does the @ViewChild element become available?
AngAfterViewInit
BngOnInit
CConstructor
DAfter component ready
💡 Hint
Refer to the 'Variable' row for 'box' in variable_tracker and step 4 in execution_table.
If we try to access the @ViewChild element in the constructor, what happens?
AIt logs the text content immediately
BIt is available and can be used
CIt is undefined and causes errors
DAngular delays constructor until view ready
💡 Hint
See variable_tracker 'box' value at Constructor and execution_table step 1.
Concept Snapshot
ngAfterViewInit lifecycle hook runs after the component's view and child views are fully initialized.
Use it to safely access @ViewChild or DOM elements.
ngOnInit runs earlier, before the view is rendered.
Accessing view elements before ngAfterViewInit leads to undefined references.
Typical use: DOM manipulation, child component interaction after view ready.
Full Transcript
In Angular, the ngAfterViewInit lifecycle hook runs after the component's template and child views are fully rendered. This means you can safely access DOM elements or child components marked with @ViewChild. Before this, during ngOnInit or the constructor, the view is not ready, so @ViewChild elements are undefined. The execution flow starts with the constructor creating the component instance, then ngOnInit initializes data but the view is not rendered yet. After the template renders, ngAfterViewInit runs, allowing access to the view elements. This is why DOM access or child component calls should be done in ngAfterViewInit to avoid errors. The variable tracker shows the @ViewChild element is undefined until ngAfterViewInit. The execution table confirms these steps and the safe point to access the view. Understanding this flow helps avoid common beginner mistakes like trying to access view elements too early.

Practice

(1/5)
1. What is the main purpose of the ngAfterViewInit lifecycle hook in Angular?
easy
A. To clean up resources when the component is destroyed
B. To initialize component input properties before the view loads
C. To handle user input events like clicks and keypresses
D. To run code after the component's view and child views are fully initialized

Solution

  1. Step 1: Understand Angular lifecycle hooks

    Angular provides hooks to run code at specific times in a component's life, such as creation, view initialization, and destruction.
  2. Step 2: Identify when ngAfterViewInit runs

    ngAfterViewInit runs after Angular fully initializes the component's view and its child views, making it safe to access view elements.
  3. Final Answer:

    To run code after the component's view and child views are fully initialized -> Option D
  4. Quick Check:

    ngAfterViewInit = view ready code [OK]
Hint: Runs after view loads, safe to access elements [OK]
Common Mistakes:
  • Confusing it with ngOnInit which runs earlier
  • Using it to handle input properties initialization
  • Thinking it runs on component destruction
2. Which of the following is the correct way to implement ngAfterViewInit in an Angular component?
easy
A. ngAfterViewInit => { console.log('View initialized'); }
B. ngAfterViewInit() { console.log('View initialized'); }
C. function ngAfterViewInit() { console.log('View initialized'); }
D. ngAfterViewInit: function() { console.log('View initialized'); }

Solution

  1. Step 1: Recall Angular component method syntax

    Angular lifecycle hooks are implemented as class methods without special syntax like arrow functions or function keywords.
  2. Step 2: Check each option's syntax

    ngAfterViewInit() { console.log('View initialized'); } uses the correct method syntax inside a class. Options A, B, and C use invalid or incorrect JavaScript syntax for class methods.
  3. Final Answer:

    ngAfterViewInit() { console.log('View initialized'); } -> Option B
  4. Quick Check:

    Use method() syntax for lifecycle hooks [OK]
Hint: Use method() syntax inside class for hooks [OK]
Common Mistakes:
  • Using arrow functions for lifecycle hooks
  • Adding function keyword inside class
  • Using object literal syntax instead of class methods
3. Given this Angular component code, what will be logged to the console?
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({ selector: 'app-sample', template: `
Content
` }) export class SampleComponent implements AfterViewInit { @ViewChild('box') box!: ElementRef; ngAfterViewInit() { console.log(this.box.nativeElement.textContent); } }
medium
A. Content
B. undefined
C. Error: box is undefined
D. null

Solution

  1. Step 1: Understand @ViewChild and ngAfterViewInit

    @ViewChild gets a reference to the DOM element after the view initializes. ngAfterViewInit runs after the view is ready, so the element is accessible.
  2. Step 2: Check what is logged

    The code logs this.box.nativeElement.textContent, which is the text inside the <div> with #box, which is "Content".
  3. Final Answer:

    Content -> Option A
  4. Quick Check:

    @ViewChild + ngAfterViewInit = element ready [OK]
Hint: Access @ViewChild only after ngAfterViewInit [OK]
Common Mistakes:
  • Trying to access @ViewChild in ngOnInit causing undefined
  • Assuming @ViewChild is null before view init
  • Confusing nativeElement with the ElementRef itself
4. What is the problem with this Angular component code?
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

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

Paragraph

` }) export class TestComponent implements AfterViewInit { @ViewChild('para') para!: ElementRef; ngOnInit() { console.log(this.para.nativeElement.textContent); } ngAfterViewInit() { console.log('View initialized'); } }
medium
A. ngAfterViewInit should be named ngAfterContentInit
B. Missing import of AfterViewInit interface
C. Accessing @ViewChild in ngOnInit causes undefined error
D. Template reference variable #para is invalid

Solution

  1. Step 1: Identify when @ViewChild is available

    @ViewChild references are set only after the view initializes, which happens after ngOnInit.
  2. Step 2: Check code usage

    The code tries to access this.para.nativeElement.textContent inside ngOnInit, which runs before the view is ready, causing undefined or error.
  3. Final Answer:

    Accessing @ViewChild in ngOnInit causes undefined error -> Option C
  4. Quick Check:

    @ViewChild ready only after ngAfterViewInit [OK]
Hint: Use @ViewChild only in ngAfterViewInit or later [OK]
Common Mistakes:
  • Accessing @ViewChild in ngOnInit
  • Confusing ngAfterViewInit with ngOnInit timing
  • Ignoring lifecycle hook order
5. You want to change the background color of a child component's element after it is fully rendered. Which approach correctly uses ngAfterViewInit to do this in the parent component?
Child component template:
<div #childBox>Child Content</div>

Parent component code options:
hard
A. Use @ViewChild('childBox') in parent and change style in ngAfterViewInit
B. Change child element style directly in parent's ngOnInit
C. Use @ViewChild in parent and change style in constructor
D. Modify child element style in parent's ngAfterContentInit without @ViewChild

Solution

  1. Step 1: Understand when child view elements are ready

    Child component's view elements are accessible in the parent during ngAfterViewInit, after the parent's view and child views are fully initialized.
  2. Step 2: Identify correct lifecycle hook and access method

    Using @ViewChild in the parent to get the child's element reference and modifying it in ngAfterViewInit ensures the element is ready and safe to modify.
  3. Final Answer:

    Use @ViewChild('childBox') in parent and change style in ngAfterViewInit -> Option A
  4. Quick Check:

    Modify child view in parent's ngAfterViewInit with @ViewChild [OK]
Hint: Use @ViewChild and ngAfterViewInit to access child elements [OK]
Common Mistakes:
  • Trying to access child elements in ngOnInit or constructor
  • Modifying child elements without @ViewChild reference
  • Using ngAfterContentInit which is for projected content, not view
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