The Component Lifecycle in Angular
Master the key stages of an Angular component, from creation and initialization with `ngOnInit` to cleanup with `ngOnDestroy`.
/* The journey begins... */
The Lifecycle Journey
The component lifecycle in Angular is a sequence of phases that a component goes through from its creation to its destruction. Angular provides lifecycle hooks, which are methods you can implement in your component classes to tap into these key moments and run code when they occur.
The Constructor: Setting the Stage
The constructor
is a TypeScript class feature, not specific to Angular's lifecycle. It runs first when the component is created. Its primary job is to inject dependencies. You should avoid putting complex logic here; save that for ngOnInit
.
ngOnInit: The Starting Line
ngOnInit()
is the first Angular-specific hook to run. It's called once, after Angular has initialized the component's data-bound properties (the ones decorated with @Input()
). This is the ideal place for component initialization logic, like fetching data from a server.
ngOnDestroy: The Cleanup Crew
ngOnDestroy()
is called just before Angular destroys the component. This is your chance to perform cleanup tasks to prevent memory leaks. Common tasks include unsubscribing from Observables, detaching event handlers, and clearing intervals.
Practice Zone
Interactive Test 1: Match the Hooks
Match the lifecycle hook with its primary purpose.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Build the Class
Rellena los huecos en cada casilla.
import { Component, OnInit, OnDestroy } from '@angular/core'; @Component({ ... }) export class MyComponent implements OnInit, OnDestroy { () { console.log('Component constructed!'); } () { console.log('Component initialized!'); } () { console.log('Component will be destroyed!'); } }
Practice Example: Code Editor
Implement a component that logs messages for `constructor`, `ngOnInit`, and `ngOnDestroy`.
Lifecycle Hooks in Action
Using the right hook for the right job is key to building robust and efficient Angular applications. Let's see some common use cases.
1. Fetching Data in `ngOnInit`
ngOnInit
is the perfect place to make initial API calls to fetch data your component needs to display. By the time this hook runs, you can be sure the component's basic setup is complete.
ngOnInit() {
this.dataService.getItems().subscribe(items => {
this.componentData = items;
});
}
2. Subscriptions and `ngOnDestroy`
To prevent memory leaks, you must clean up any long-lived subscriptions when a component is destroyed. A common pattern is to manage subscriptions and unsubscribe in ngOnDestroy
.
private dataSub: Subscription;
ngOnInit() {
this.dataSub = this.someObservable$.subscribe(...);
}
ngOnDestroy() {
// This prevents memory leaks!
this.dataSub.unsubscribe();
}
3. Interacting with the DOM in `ngAfterViewInit`
If you need to interact directly with the DOM (e.g., to initialize a third-party library on a canvas element), you should wait until ngAfterViewInit
. This hook guarantees that the component's view, and all its children's views, have been fully rendered.
@ViewChild('myCanvas') canvasRef: ElementRef;
ngAfterViewInit() {
// Now it's safe to access the canvas element
const canvas = this.canvasRef.nativeElement;
console.log('Canvas element is ready:', canvas);
}
Practical Takeaway: Initialize inngOnInit
, clean up inngOnDestroy
, and wait forngAfterViewInit
for DOM manipulations. This separation of concerns is fundamental to good Angular architecture.
Angular Lifecycle Glossary
- constructor()
- The standard TypeScript class constructor. Called first. Used for dependency injection and very basic property initialization.
- ngOnChanges()
- Called before
ngOnInit()
and whenever one or more data-bound input properties (@Input()
) change. - ngOnInit()
- Called once, after the first
ngOnChanges()
. It's the primary hook for component initialization logic. - ngAfterViewInit()
- Called once after Angular initializes the component's views and child views. Use it for DOM-related initialization.
- ngOnDestroy()
- Called immediately before Angular destroys the component. This is the place for cleanup logic to avoid memory leaks.