ReviseAlgo Logo

Fundamentals

Components

Master Angular Components, covering component lifecycle hooks, change detection triggers, and style encapsulation settings.

Last Updated: July 15, 2026 • 12 min read

1. Learning Objectives

In this lesson, you will master the lifecycle and features of Angular components. By the end of this topic, you will be able to:

  • Explain the lifecycle hooks of an Angular component.
  • Use ngOnInit to run component initialization logic.
  • Use ngOnDestroy to prevent memory leaks by unsubscribing from observables.
  • Compare styling encapsulation modes (Emulated, ShadowDom, None).
  • Implement lifecycle interfaces in TypeScript classes.

2. Overview

Components are the fundamental building blocks of Angular applications. Each component consists of a TypeScript class (defining behavior), an HTML template (defining structure), and a stylesheet. The component's lifecycle is managed by Angular, which creates, updates, and destroys components in response to application events.

3. Why This Topic Matters

Managing component lifecycle events correctly is essential for application performance:

  • Memory Leaks from Active Subscriptions: If a component subscribes to an observable but fails to unsubscribe inside ngOnDestroy, the subscription remains active in the background. If the component is repeatedly created and destroyed, this will cause memory leaks and slow down the application.
  • Incorrect Initialization in the Constructor: The constructor should only be used for dependency injection. Fetching API data in the constructor can fail because component input properties are not yet bound. Always use ngOnInit for initialization logic.

4. Real-World Analogy

Think of a component's lifecycle like **the lifecycle of a rental car**:

  • Constructor (Manufacturing): The car is built and the engine and dashboard are installed (dependency injection).
  • ngOnInit (Rental starts): The customer adjusts the mirrors, sets the GPS coordinates, and starts driving (input binding initialization).
  • ngOnChanges (Changing settings): The driver adjusts the air conditioning temperature while driving (updating component input bindings).
  • ngOnDestroy (Returning the car): The customer cleans out their personal items, removes their phone profile from the console, and returns the keys (unsubscribing from resources and cleaning up memory).

5. Core Concepts

Angular component lifecycle hooks let you run code at key points in a component's life:

  • ngOnChanges(): Called when input properties (@Input) change.
  • ngOnInit(): Called once after the component has initialized and inputs are bound. Best for running API requests.
  • ngOnDestroy(): Called before the component is destroyed. Best for cleanup logic (unsubscribing from observables, stopping timers).
  • Styling Encapsulation: By default (ViewEncapsulation.Emulated), Angular scopes component styles to its template, preventing them from leaking to the rest of the application.
Encapsulation Mode CSS Behavior Use Case
Emulated (Default) Styles are scoped to the component template using unique attributes added by Angular. Standard components (prevents CSS styles from leaking).
None Styles are added to the document head and apply globally to the page. Overriding third-party component libraries globally.
ShadowDom Uses browser native Shadow DOM encapsulation (strict style isolation). Building web components designed to run in other frameworks.

6. Syntax & API Reference

Below is a standalone component that implements lifecycle hooks and styling encapsulation:

7. Visual Diagram

This diagram displays the order of execution for Angular component lifecycle hooks:

8. Live Example — Full Working Code

Below is a component that uses a timer subscription and cleans it up inside ngOnDestroy:

9. Interactive Playground

Try It Yourself Challenges:

  1. Change the component encapsulation type to ViewEncapsulation.None and notice how internal styles leak to rest of page.
  2. Test removing the unsubscribe statement inside ngOnDestroy and observe console output logs after the component is removed.

10. Common Mistakes

Mistake Why it happens Wrong Correct
Accessing inputs in constructor Attempting to read component input properties inside the constructor before they are bound by Angular, returning undefined. constructor() { console.log(this.inputVal); } ngOnInit() { console.log(this.inputVal); }
Leaving subscriptions active Forgetting to unsubscribe from active subscriptions when the component is destroyed, causing memory leaks. No cleanup in ngOnDestroy. subscription.unsubscribe() inside ngOnDestroy.

11. Best Practices

  • Keep the constructor clean: Use the constructor only for dependency injection. Do not run initialization logic inside it.
  • Initialize logic in ngOnInit: Run all setup logic (such as fetching data or setting up event listeners) inside the ngOnInit hook.
  • Unsubscribe in ngOnDestroy: Always unsubscribe from observables or stop active timers inside ngOnDestroy to prevent memory leaks.

12. Browser Compatibility/Requirements

All modern browsers support view encapsulation. Angular uses emulated attributes, which work in older browsers without requiring native Shadow DOM support.

13. Interview Questions

🟢 Q1: Why should you run initialization logic inside ngOnInit instead of the constructor?

Answer: The constructor runs when the class is instantiated, before Angular binds component input properties (@Input). Inside the constructor, inputs are undefined. Angular calls ngOnInit after inputs are bound, making it the correct place to run initialization logic that relies on inputs.

14. Debugging Exercise

Identify and fix the memory leak in this component class:

View Solution

Diagnosis: The component starts an interval timer inside ngOnInit but does not clear it when the component is destroyed. The interval timer continues to run in the background, causing a memory leak. To fix this, store the interval ID and clear it inside the ngOnDestroy hook.

Fixed component:

15. Practice Exercises

Exercise 1: Create a Lifecycle logger

Build a standalone component that prints a log message to the console for every stage of its lifecycle (constructor, ngOnChanges, ngOnInit, ngOnDestroy).

16. Scenario-Based Challenge

The Style Leakage Challenge:

An Angular project contains a workspace component that sets styles for the HTML h2 tag. Developers notice that after loading this component, all headers across the application change color. Write a solution using component ViewEncapsulation settings to scope these styles to the component.

17. Quick Quiz

Q1: Which lifecycle hook is called first during component initialization?

A) ngOnInit

B) ngOnDestroy

C) ngOnChanges

Answer: C — Angular calls ngOnChanges first when input values are bound, before running ngOnInit.

18. Summary & Key Takeaways

  • • Use ngOnInit for component initialization and ngOnDestroy to clean up resources like active subscriptions.
  • • By default, ViewEncapsulation.Emulated scopes component styles to its template, preventing them from leaking.

19. Cheat Sheet

Lifecycle Hook Purpose
ngOnChanges() Called whenever input properties change. Receives a SimpleChanges object.