Component Lifecycle
A component is created, shown, updated and finally destroyed. ngOnInit runs once when it's ready, with its inputs set; ngOnDestroy runs when it's removed, to clean up timers and the like. effect runs code whenever the signals it reads change.
Apprentice · Angular · Updated
After this lesson you can
- Run code when a component starts and when it's removed, with ngOnInit and ngOnDestroy
- Run code whenever signals change with effect
Key takeaways
- Inputs aren't set yet in the constructor.
ngOnInitruns once, just after they are: the place for start-up work that needs them. ngOnDestroyruns just before a component is removed: stop what it started there, such as a timer withclearInterval, or it keeps running.effectruns a function once, then again whenever a signal it reads changes. Create effects in the constructor.- Use
computedfor a value to show andeffectfor an action, such as saving or logging, when signals change.
A component has a lifecycle: Angular creates it, sets its inputs, shows it, updates it as its data changes, and, when it's no longer needed, such as when an @if turns false, destroys it. Angular lets you run code at the important moments.
ngOnInit: ready to start
The constructor runs first, before Angular has set the inputs, so an input can't be read there yet. ngOnInit runs once, just after the inputs are set: the right place for start-up work that needs them, such as loading data for a given product.
import { Component, input, OnInit, signal } from '@angular/core';
@Component({
imports: [],
selector: 'app-welcome',
template: `<p>{{ message() }}</p>`,
})
export class Welcome implements OnInit {
readonly name = input.required<string>();
protected readonly message = signal('');
ngOnInit() {
this.message.set(`Welcome back, ${this.name()}!`);
}
}
implements OnInit is optional, but it makes TypeScript check that ngOnInit is spelled right. (<app-welcome name="Ada" /> shows Welcome back, Ada!: a plain attribute, without brackets, passes the text itself.)
ngOnDestroy: cleaning up
Some work keeps going until it's stopped: a timer, for instance. If a component starts one, it must stop it when it's removed, or the timer keeps running in the background, forever. ngOnDestroy runs just before the component is destroyed:
import { Component, OnDestroy, OnInit, signal } from '@angular/core';
@Component({
imports: [],
selector: 'app-stopwatch',
template: `<p>{{ seconds() }} seconds</p>`,
})
export class Stopwatch implements OnInit, OnDestroy {
protected readonly seconds = signal(0);
private timerId = 0;
ngOnInit() {
this.timerId = setInterval(() => this.seconds.update(s => s + 1), 1000);
}
ngOnDestroy() {
clearInterval(this.timerId);
}
}
setInterval calls its callback every second and returns an id; clearInterval(id) stops it. Show the stopwatch inside @if (running()) { <app-stopwatch /> }, and when running turns false, Angular destroys it, ngOnDestroy runs, and the timer stops.
effect: whenever signals change
Sometimes you want to do something, not just show something, whenever a signal changes: save it, log it, tell another part of the app. effect runs a function once at the start, then again every time a signal it reads changes:
import { Component, effect, signal } from '@angular/core';
@Component({
imports: [],
selector: 'app-theme-picker',
template: `
<button class="btn btn-outline-secondary" (click)="dark.set(!dark())">Switch theme</button>
`,
})
export class ThemePicker {
protected readonly dark = signal(false);
constructor() {
effect(() => {
localStorage.setItem('theme', this.dark() ? 'dark' : 'light');
});
}
}
Each click flips dark, and the effect saves the theme in the browser's localStorage. Like computed, an effect notices which signals it reads, and follows them. Create effects in the constructor; Angular stops them when the component is destroyed.
| Use | For |
|---|---|
computed |
A value worked out from signals, to show |
effect |
An action to take when signals change, such as saving or logging |
ngOnInit |
Start-up work that needs the inputs |
ngOnDestroy |
Clean-up: timers, and anything else that would keep running |
Prefer computed whenever you just need a value: effects are for the outside world.
Check yourself
2 questions to try on the lesson page.
So what
ngOnInit to start, ngOnDestroy to clean up, effect to act on changes. Knowing when a component's code runs is what keeps it from showing stale data, or leaving timers running after it's gone.