Bird
Raised Fist0
Angularframework~20 mins

ngOnInit for initialization in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
ngOnInit Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when ngOnInit runs in this Angular component?

Consider this Angular component code snippet. What will be the value of message after ngOnInit runs?

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

@Component({
  selector: 'app-welcome',
  template: `<p>{{ message }}</p>`,
  standalone: true
})
export class WelcomeComponent implements OnInit {
  message = '';

  ngOnInit() {
    this.message = 'Hello from ngOnInit!';
  }
}
A"" (empty string)
Bnull
Cundefined
D"Hello from ngOnInit!"
Attempts:
2 left
💡 Hint

ngOnInit runs after the component is created but before it is displayed.

❓ lifecycle
intermediate
1:30remaining
When is ngOnInit called in Angular component lifecycle?

Choose the correct timing for when ngOnInit is called in an Angular component's lifecycle.

AAfter the component's constructor and before the first render
BBefore the component's constructor runs
CAfter the component is destroyed
DOnly when the component's inputs change
Attempts:
2 left
💡 Hint

Think about when initialization logic should run relative to component creation.

📝 Syntax
advanced
2:00remaining
Identify the correct ngOnInit implementation in this Angular component

Which option correctly implements ngOnInit in this Angular component?

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

@Component({
  selector: 'app-counter',
  template: `<p>{{ count }}</p>`,
  standalone: true
})
export class CounterComponent implements OnInit {
  count = 0;

  // ngOnInit implementation goes here
}
AngOnInit() => { this.count = 10; }
BngOnInit() { this.count = 10; }
Cfunction ngOnInit() { this.count = 10; }
DngOnInit { this.count = 10; }
Attempts:
2 left
💡 Hint

Remember the correct method syntax inside a class in TypeScript.

🔧 Debug
advanced
2:30remaining
Why does this ngOnInit code not update the template?

Given this Angular component, why does the template not show the updated title after ngOnInit?

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

@Component({
  selector: 'app-title',
  template: `<h1>{{ title }}</h1>`,
  standalone: true
})
export class TitleComponent implements OnInit {
  title = 'Initial';

  ngOnInit() {
    let title = 'Updated in ngOnInit';
  }
}
AThe component selector is missing, so it does not render
BngOnInit is not called automatically, so the title stays the same
CThe local variable 'title' inside ngOnInit shadows the class property, so the class property is not changed
DThe template binding syntax is incorrect and does not update
Attempts:
2 left
💡 Hint

Check variable scope inside ngOnInit.

🧠 Conceptual
expert
3:00remaining
What is the main benefit of using ngOnInit instead of constructor for initialization?

Why should you put initialization code in ngOnInit rather than the constructor in Angular components?

AngOnInit runs after Angular sets input properties, so initialization can use them safely
BThe constructor runs multiple times, but ngOnInit runs only once
CngOnInit runs before the constructor, so it initializes earlier
DThe constructor cannot access class properties, but ngOnInit can
Attempts:
2 left
💡 Hint

Think about when Angular sets input properties relative to constructor and ngOnInit.

Practice

(1/5)
1. What is the main purpose of the ngOnInit method in an Angular component?
easy
A. To run initialization code after the component is created
B. To handle user input events
C. To define the component's HTML template
D. To style the component with CSS

Solution

  1. Step 1: Understand the role of ngOnInit

    The ngOnInit lifecycle hook runs after Angular creates the component, making it ideal for initialization tasks.
  2. Step 2: Differentiate from other component parts

    Handling user input, defining templates, and styling are done elsewhere, not in ngOnInit.
  3. Final Answer:

    To run initialization code after the component is created -> Option A
  4. Quick Check:

    ngOnInit = initialization after creation [OK]
Hint: ngOnInit runs once after component setup [OK]
Common Mistakes:
  • Confusing ngOnInit with event handlers
  • Thinking ngOnInit sets styles or templates
  • Using ngOnInit for user input processing
2. Which of the following is the correct way to implement ngOnInit in an Angular component?
easy
A. ngOnInit() { console.log('Init'); }
B. ngOnInit: function() { console.log('Init'); }
C. function ngOnInit() { console.log('Init'); }
D. onInit() { console.log('Init'); }

Solution

  1. Step 1: Recall Angular lifecycle hook syntax

    In Angular components, lifecycle hooks like ngOnInit are methods declared as ngOnInit() { ... }.
  2. Step 2: Identify incorrect syntax

    The other options use invalid syntax in an Angular class: shorthand property with function, standalone function declaration, and wrong method name.
  3. Final Answer:

    ngOnInit() { console.log('Init'); } -> Option A
  4. Quick Check:

    ngOnInit is a method, not a property or function keyword [OK]
Hint: Use method syntax: ngOnInit() { } [OK]
Common Mistakes:
  • Using function keyword inside class
  • Naming method incorrectly as onInit
  • Using colon instead of parentheses
3. Consider this Angular component code snippet:
export class MyComponent implements OnInit {
  data = '';
  ngOnInit() {
    this.data = 'Hello World';
  }
}

What will be the value of data after the component initializes?
medium
A. '' (empty string)
B. undefined
C. null
D. 'Hello World'

Solution

  1. Step 1: Check initial value of data

    The property data starts as an empty string.
  2. Step 2: See what ngOnInit does

    Inside ngOnInit, data is set to 'Hello World'. This runs after component creation.
  3. Final Answer:

    'Hello World' -> Option D
  4. Quick Check:

    ngOnInit sets data to 'Hello World' [OK]
Hint: ngOnInit runs after creation, sets data [OK]
Common Mistakes:
  • Assuming data stays empty string
  • Confusing initialization timing
  • Thinking ngOnInit runs before constructor
4. Identify the error in this Angular component code:
export class SampleComponent implements OnInit {
  message: string;
  ngOnInit() {
    this.message = 'Welcome';
  }
}
medium
A. ngOnInit method name is incorrect
B. message property should be initialized in constructor
C. Missing import of OnInit interface
D. No error, code is correct

Solution

  1. Step 1: Check for required imports

    The component implements OnInit but does not import it from '@angular/core'. This causes a compile error.
  2. Step 2: Verify method and property usage

    The method name ngOnInit is correct, and initializing message in ngOnInit is valid.
  3. Final Answer:

    Missing import of OnInit interface -> Option C
  4. Quick Check:

    Implementing OnInit requires importing it [OK]
Hint: Always import lifecycle interfaces from '@angular/core' [OK]
Common Mistakes:
  • Forgetting to import OnInit
  • Renaming ngOnInit incorrectly
  • Thinking properties must initialize in constructor
5. You want to fetch user data from a server right after your Angular component is created. Where should you place the fetch call to ensure it runs once after initialization?
hard
A. Inside the constructor
B. Inside the ngOnInit method
C. Inside the ngOnDestroy method
D. Inside a button click event handler

Solution

  1. Step 1: Understand lifecycle timing

    The constructor runs before Angular sets up the component fully, so it's not ideal for async tasks like fetching data.
  2. Step 2: Use ngOnInit for initialization tasks

    ngOnInit runs after component creation and is the recommended place to start fetching data once.
  3. Step 3: Exclude other options

    ngOnDestroy runs when component is destroyed, and button click handlers run on user action, not automatically.
  4. Final Answer:

    Inside the ngOnInit method -> Option B
  5. Quick Check:

    Fetch data in ngOnInit for one-time setup [OK]
Hint: Fetch data in ngOnInit, not constructor [OK]
Common Mistakes:
  • Fetching data in constructor causing timing issues
  • Using ngOnDestroy which runs too late
  • Waiting for user click instead of auto-fetch
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