Angular Component Lifecycle: What It Is and How It Works
component lifecycle is a series of events from creation to destruction of a component. Angular provides lifecycle hooks that let you run code at specific moments like when a component starts, updates, or is removed.How It Works
Think of an Angular component like a stage actor. The actor arrives, performs, reacts to changes, and finally leaves the stage. The component lifecycle is the timeline of these events.
Angular calls special methods called lifecycle hooks at key moments. For example, when the component is created, Angular calls ngOnInit. When input data changes, it calls ngOnChanges. When the component is about to be removed, it calls ngOnDestroy. These hooks let you run your own code at the right time, like setting up data, responding to changes, or cleaning up resources.
Example
import { Component, Input, OnInit, OnChanges, OnDestroy, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-lifecycle-demo', template: `<p>Message: {{message}}</p>` }) export class LifecycleDemoComponent implements OnInit, OnChanges, OnDestroy { @Input() message = ''; ngOnInit() { console.log('Component initialized'); } ngOnChanges(changes: SimpleChanges) { console.log('Input changed:', changes.message.currentValue); } ngOnDestroy() { console.log('Component destroyed'); } }
When to Use
Use lifecycle hooks when you need to run code at specific times in a component's life. For example:
- ngOnInit: Fetch data or initialize variables when the component starts.
- ngOnChanges: React to changes in input properties, like updating displayed data.
- ngOnDestroy: Clean up timers, subscriptions, or event listeners to avoid memory leaks.
These hooks help keep your app efficient and responsive by managing resources and updates properly.
Key Points
- Angular components have a lifecycle from creation to destruction.
- Lifecycle hooks let you run code at important moments.
- Common hooks include
ngOnInit,ngOnChanges, andngOnDestroy. - Using hooks helps manage data, respond to changes, and clean up resources.