Angular Lifecycle Hooks
Every component has a life. Angular creates it, shows it, updates it, and finally removes it. Lifecycle hooks are special methods that Angular calls at each stage. You write code inside a hook when you need to act at a specific moment. Loading data at the start and cleaning up at the end are the two most common examples.
The Life of a Plant
Compare a component to a plant in a garden. The gardener plants the seed, waters it, watches it grow, and removes it at the end of the season. Each task happens at a fixed time. Hooks give you the same fixed moments for a component.
Lifecycle Order
constructor Component object is created
|
ngOnChanges Input values arrive or change
|
ngOnInit Component is ready; load data here
|
ngDoCheck Angular checks for changes
|
ngAfterViewInit Template and child views are ready
|
ngOnDestroy Component is removed; clean up here
How to Use a Hook
Implement the matching interface and add the method. The interface reminds you of the correct method name.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-welcome',
template: '<p>{{ message }}</p>'
})
export class WelcomeComponent implements OnInit {
message = '';
ngOnInit() {
this.message = 'Component is ready';
}
}
ngOnChanges
Angular calls this hook before ngOnInit and again whenever an input value changes. The method receives an object that lists every changed input with its old and new values. Use it when you must react to new data from a parent.
ngOnChanges(changes: SimpleChanges) {
console.log('Old and new values', changes);
}
ngOnInit
Angular calls this hook once, after the first inputs arrive. Most components use it to load data from a server. The constructor should stay small and only receive services. Place the real startup work in ngOnInit.
ngAfterViewInit
Angular calls this hook after the template appears on the screen. Use it when your code needs to touch an element on the page, such as a chart container or a video player.
ngOnDestroy
Angular calls this hook just before it removes the component. Use it to stop timers, close connections, and cancel subscriptions. Skipped cleanup causes memory leaks, which slow the application over time.
import { OnDestroy } from '@angular/core';
export class ClockComponent implements OnDestroy {
timer = setInterval(() => console.log('tick'), 1000);
ngOnDestroy() {
clearInterval(this.timer);
}
}
Without the cleanup line, the timer keeps running after the visitor leaves the page.
Hook Summary
| Hook | When It Runs | Typical Use |
|---|---|---|
| ngOnChanges | An input changes | React to new parent data |
| ngOnInit | Once after the first inputs | Load data |
| ngDoCheck | Every change check | Custom change detection |
| ngAfterViewInit | After the view appears | Work with page elements |
| ngOnDestroy | Before removal | Clean up |
Common Mistakes
Heavy Work in the Constructor
The constructor runs before inputs exist. A data request there may miss the values it needs. Move such work to ngOnInit.
Forgotten Cleanup
Intervals and subscriptions continue after a component leaves. Stop them in ngOnDestroy.
Real-Life Example
Consider a weather widget on a page. The widget loads the forecast in ngOnInit because the data must arrive once at startup. A visitor then picks a new city, and the parent passes the city name through an input. The widget catches that change in ngOnChanges and loads a fresh forecast. When the visitor leaves the page, ngOnDestroy stops the refresh timer. Each hook handles one clear job.
Tips for Using Hooks
Implement only the hooks that you need. Keep every hook short and move long logic into separate methods. Name those methods after their purpose so readers understand them quickly.
Practice Exercise
Create a component that writes a message to the console in each hook. Show the component on a page and hide it with a button. Watch the console. You will see the creation messages when it appears and the destroy message when it disappears. This test makes the order of hooks easy to remember.
Key Points
- Hooks are methods that Angular calls at fixed stages.
- Use
ngOnInitfor startup work. - Use
ngOnDestroyfor cleanup. - Keep the constructor small.
