Concept Flow - ngOnInit for initialization
Component Created
Constructor Runs
ngOnInit Called
Initialize Data
Component Ready to Render
Angular calls ngOnInit after the component is created and constructor runs, to initialize data before rendering.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-sample', template: '{{message}}' }) export class SampleComponent implements OnInit { message = ''; ngOnInit() { this.message = 'Hello from ngOnInit!'; } }
| Step | Action | State Before | State After | Rendered Output |
|---|---|---|---|---|
| 1 | Component instance created | message = '' | message = '' | |
| 2 | Constructor runs | message = '' | message = '' | |
| 3 | ngOnInit called | message = '' | message = 'Hello from ngOnInit!' | |
| 4 | Angular renders template | message = 'Hello from ngOnInit!' | message = 'Hello from ngOnInit!' | Hello from ngOnInit! |
| Variable | Start | After ngOnInit | Final |
|---|---|---|---|
| message | '' (empty string) | 'Hello from ngOnInit!' | 'Hello from ngOnInit!' |
ngOnInit is a lifecycle hook Angular calls after component creation and input setup. Use ngOnInit to initialize data or fetch info needed before rendering. Constructor runs earlier but should not depend on Angular inputs. ngOnInit ensures component is ready for initialization. Syntax: implement OnInit interface and define ngOnInit() method.
ngOnInit method in an Angular component?ngOnInit lifecycle hook runs after Angular creates the component, making it ideal for initialization tasks.ngOnInit.ngOnInit in an Angular component?ngOnInit are methods declared as ngOnInit() { ... }.export class MyComponent implements OnInit {
data = '';
ngOnInit() {
this.data = 'Hello World';
}
}data after the component initializes?data starts as an empty string.ngOnInit, data is set to 'Hello World'. This runs after component creation.export class SampleComponent implements OnInit {
message: string;
ngOnInit() {
this.message = 'Welcome';
}
}OnInit but does not import it from '@angular/core'. This causes a compile error.ngOnInit is correct, and initializing message in ngOnInit is valid.ngOnInit runs after component creation and is the recommended place to start fetching data once.ngOnDestroy runs when component is destroyed, and button click handlers run on user action, not automatically.Pass the test and this pattern moves unknown