0
0
Angularframework~5 mins

ngOnInit for initialization in Angular

Choose your learning style9 modes available
Introduction

ngOnInit helps you run code right after your Angular component is ready. It is used to set up things like data or start tasks.

You want to load data from a server when a page opens.
You need to set initial values for variables in your component.
You want to start a timer or subscribe to events when the component appears.
You want to run code only once after the component is created.
Syntax
Angular
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
    // initialization code here
  }
}

ngOnInit is a lifecycle hook method Angular calls once after creating the component.

You must implement the OnInit interface and define the ngOnInit() method.

Examples
This example logs a message when the component is ready.
Angular
export class MyComponent implements OnInit {
  ngOnInit(): void {
    console.log('Component initialized');
  }
}
Here, ngOnInit sets the initial userName value after the component loads.
Angular
export class UserProfile implements OnInit {
  userName = '';

  ngOnInit(): void {
    this.userName = 'Alice';
  }
}
Sample Program

This component shows a welcome message. The name is set inside ngOnInit, so it appears when the component loads.

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

@Component({
  selector: 'app-welcome',
  template: `<h1>Welcome, {{name}}!</h1>`
})
export class WelcomeComponent implements OnInit {
  name = '';

  ngOnInit(): void {
    this.name = 'Friend';
  }
}
OutputSuccess
Important Notes

Do not put heavy or slow code in ngOnInit; keep it for quick setup.

ngOnInit runs only once per component instance.

Summary

ngOnInit runs code after the component is created.

Use it to set initial data or start tasks.

It helps keep your component setup organized and predictable.