0
0
AngularConceptBeginner · 4 min read

Angular Component Lifecycle: What It Is and How It Works

In Angular, the 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

This example shows a simple Angular component using some lifecycle hooks to log messages when the component starts, updates, and ends.
typescript
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');
  }
}
Output
Component initialized Input changed: Hello Input changed: Hello again 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, and ngOnDestroy.
  • Using hooks helps manage data, respond to changes, and clean up resources.

Key Takeaways

Angular component lifecycle is the sequence of events from creation to destruction.
Lifecycle hooks let you run code at specific moments like start, update, and destroy.
Use ngOnInit to initialize, ngOnChanges to react to input changes, and ngOnDestroy to clean up.
Proper use of lifecycle hooks improves app performance and resource management.