0
0
Angularframework~30 mins

ngOnInit for initialization in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Using ngOnInit for Initialization in Angular
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use interpolation {{ message }} and *ngFor="let fruit of fruits" to loop through the fruits array.