What does ngOnInit() do? When is it called?
In Angular, ngOnInit() is a lifecycle hook that is called once, after a component's input properties (@Input) are initialized.
Key points
- What it does:
- Used to initialize the component's logic once all the input data is already available.
- Suitable for loading data, setting up the initial state, and calling services.
- When it is called:
- Once, after the input property values are first passed and before the component's first render.
- Called after
ngOnChanges(), if there are input properties.
Example:
ts
export class ChildComponent implements OnInit {
@Input() name: string;
ngOnInit() {
console.log('Component initialized, name:', this.name);
}
}- At this point,
namealready contains the value passed by the parent.
In other words, ngOnInit is the place for initial component setup, once all the data is already available, and it runs only once.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.