📖 Scenario: You are building a simple Angular component that shows a welcome message and a list of favorite fruits. You want to set up the initial data when the component starts.
🎯 Goal: Create an Angular standalone component that initializes a message string and a fruits array inside the ngOnInit lifecycle method. Display the message and the list of fruits in the template.
📋 What You'll Learn
Create a standalone Angular component named WelcomeComponent
Initialize a message string and a fruits array inside ngOnInit
Display the message in an <h1> tag
Display the fruits array items in an unordered list <ul>
Use Angular's OnInit interface and implement ngOnInit method
💡 Why This Matters
🌍 Real World
Components often need to set up data when they start. Using ngOnInit is the standard way to initialize data in Angular components.
💼 Career
Understanding Angular lifecycle hooks like ngOnInit is essential for building maintainable and predictable Angular applications in professional development.
Progress0 / 4 steps
1
Create the Angular component with initial properties
Create a standalone Angular component named WelcomeComponent with two public properties: message of type string and fruits of type string array. Do not initialize them yet.
Angular
Hint
Define the component class with message and fruits properties but do not assign values yet.
2
Import OnInit and add ngOnInit method
Import OnInit from @angular/core. Make WelcomeComponent implement OnInit and add an empty ngOnInit() method.
Angular
Hint
Remember to import OnInit and add the ngOnInit method inside the class.
3
Initialize message and fruits inside ngOnInit
Inside the ngOnInit() method, set message to 'Welcome to the Fruit List!' and fruits to the array ['Apple', 'Banana', 'Cherry'].
Angular
Hint
Use this.message and this.fruits to assign the values inside ngOnInit.
4
Add template to display message and fruits list
Add the template inside the @Component decorator to display the message inside an <h1> tag and the fruits array items inside an unordered list <ul> with each fruit in a <li>. Use Angular's *ngFor directive with let fruit of fruits.
Angular
Hint
Use interpolation {{ message }} and *ngFor="let fruit of fruits" to loop through the fruits array.
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
Step 1: Understand the role of ngOnInit
The ngOnInit lifecycle hook runs after Angular creates the component, making it ideal for initialization tasks.
Step 2: Differentiate from other component parts
Handling user input, defining templates, and styling are done elsewhere, not in ngOnInit.
Final Answer:
To run initialization code after the component is created -> Option A
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
Step 1: Recall Angular lifecycle hook syntax
In Angular components, lifecycle hooks like ngOnInit are methods declared as ngOnInit() { ... }.
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.
Final Answer:
ngOnInit() { console.log('Init'); } -> Option A
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
Step 1: Check initial value of data
The property data starts as an empty string.
Step 2: See what ngOnInit does
Inside ngOnInit, data is set to 'Hello World'. This runs after component creation.
Final Answer:
'Hello World' -> Option D
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:
B. message property should be initialized in constructor
C. Missing import of OnInit interface
D. No error, code is correct
Solution
Step 1: Check for required imports
The component implements OnInit but does not import it from '@angular/core'. This causes a compile error.
Step 2: Verify method and property usage
The method name ngOnInit is correct, and initializing message in ngOnInit is valid.
Final Answer:
Missing import of OnInit interface -> Option C
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
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.
Step 2: Use ngOnInit for initialization tasks
ngOnInit runs after component creation and is the recommended place to start fetching data once.
Step 3: Exclude other options
ngOnDestroy runs when component is destroyed, and button click handlers run on user action, not automatically.
Final Answer:
Inside the ngOnInit method -> Option B
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 unknownstrongwhile earning +1 Grip toward your certificate.