Ir al contenido

Lifecycle Hooks

Esta página aún no está disponible en tu idioma.

Components have a lifecycle from creation to destruction. Angular provides hooks to execute logic at key moments:

HookPurpose
ngOnInitRuns once after the component is initialized. Ideal for setup tasks.
ngOnChangesRuns when @Input properties change (before ngOnInit and on updates).
ngAfterViewInitRuns after the component’s view is fully initialized.
ngAfterContentInitRuns after projected content is initialized.
ngDoCheckRuns during every change detection cycle. Use carefully.
ngOnDestroyRuns just before the component is destroyed. Clean up subscriptions here.

import { Component, OnInit, OnDestroy, input, DestroyRef, inject } from '@angular/core';
@Component({
selector: 'app-user-card',
template: `<p>{{ name() }}</p>`
})
export class UserCardComponent implements OnInit, OnDestroy {
name = input.required<string>();
private destroyRef = inject(DestroyRef);
ngOnInit(): void {
console.log('Component initialized!');
this.destroyRef.onDestroy(() => {
console.log('Cleaning up resources...');
});
}
ngOnDestroy(): void {
console.log('Component destroyed!');
}
}

Instead of implementing OnDestroy manually, use DestroyRef for a more composable approach:

import { Component, inject, DestroyRef, OnInit } from '@angular/core';
import { interval } from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-timer',
template: `<p>Elapsed: {{ seconds() }}s</p>`
})
export class TimerComponent implements OnInit {
seconds = signal(0);
private destroyRef = inject(DestroyRef);
ngOnInit(): void {
interval(1000)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.seconds.update(s => s + 1));
}
}

Modern Alternative — afterNextRender and afterRender

Section titled “Modern Alternative — afterNextRender and afterRender”

For DOM-dependent initialization, Angular 18+ provides render hooks. These are especially useful for SSR compatibility since they only run in the browser:

import { Component, afterNextRender, afterRender, ElementRef } from '@angular/core';
@Component({
selector: 'app-chart',
template: `<canvas #chart></canvas>`
})
export class ChartComponent {
constructor() {
afterNextRender(() => {
console.log('First render complete — initialize chart library here');
});
afterRender(() => {
console.log('Re-render complete');
});
}
}

When to use render hooks vs lifecycle hooks:

ScenarioUse
Fetch data on initngOnInit
React to input changes (legacy)ngOnChanges
Access DOM after first paintafterNextRender
Sync DOM state every renderafterRender
Cleanup subscriptions/timersDestroyRef.onDestroy() or ngOnDestroy
SSR-safe DOM accessafterNextRender (skipped on server)

constructor()
→ ngOnChanges() (if inputs exist)
→ ngOnInit()
→ ngDoCheck()
→ ngAfterContentInit()
→ ngAfterContentChecked()
→ ngAfterViewInit()
→ afterNextRender() [browser only]
→ afterRender() [browser only]
→ ngAfterViewChecked()
... (change detection cycles) ...
→ ngOnDestroy()