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.