Understanding Angular Components: Structure and Lifecycle Hooks

Angular components are the core building blocks of an Angular application. They define the user interface and the logic behind it. Each component consists of a TypeScript class, an HTML template, and a CSS stylesheet. Additionally, Angular provides lifecycle hooks that allow developers to execute specific logic at different phases of a component’s life.

This guide explains the structure of Angular components and explores the lifecycle hooks that help in managing component behavior effectively.


1. What is an Angular Component?

An Angular component is a self-contained unit that controls a section of the UI. A component:

  • Has a TypeScript class that defines the logic.

  • Uses an HTML template to render UI elements.

  • Includes a CSS file for styling.

  • Can receive inputs and emit outputs to communicate with other components.

Example of an Angular Component

import { Component } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {
  title = 'Hello, Angular!';
}

The selector defines the tag used to insert this component in other templates.


2. Angular Component Structure

An Angular component typically includes:

a) Component Decorator (@Component)

Defines metadata about the component, including its selector, template, and styles.

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})

b) Component Class

Contains the logic for the component, such as properties and methods.

export class ExampleComponent {
  title = 'Hello, Angular!';
}

c) Template (HTML file)

Defines the UI structure of the component.

<h2>{{ title }}</h2>
<p>Welcome to your first Angular component.</p>

d) Stylesheet (CSS file)

Defines the appearance of the component.

h2 {
  color: blue;
}

3. Creating a Component in Angular

To generate a new component using Angular CLI, run:

ng generate component my-component

or

ng g c my-component

This creates four files in the src/app/my-component/ directory:

  1. my-component.component.ts – Component logic

  2. my-component.component.html – UI template

  3. my-component.component.css – Stylesheet

  4. my-component.component.spec.ts – Unit test file

The component is automatically registered in app.module.ts.


4. Angular Component Lifecycle Hooks

Angular components go through various phases, from creation to destruction. Lifecycle hooks allow developers to execute code at specific points during this process.

List of Angular Lifecycle Hooks

HookDescription
ngOnInitCalled once when the component is initialized.
ngOnChangesInvoked when an input property changes.
ngDoCheckRuns during every change detection cycle.
ngAfterContentInitRuns after content (ng-content) is projected.
ngAfterContentCheckedCalled after projected content is checked.
ngAfterViewInitRuns after component’s view and child views are initialized.
ngAfterViewCheckedCalled after the component’s view is checked.
ngOnDestroyExecutes just before the component is destroyed.

5. Implementing Lifecycle Hooks

a) ngOnInit – Initialize Component Data

The ngOnInit lifecycle hook is commonly used to initialize data when the component is loaded.

Example

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-lifecycle-demo',
  template: '<h2>{{ message }}</h2>',
})
export class LifecycleDemoComponent implements OnInit {
  message: string = '';

  ngOnInit() {
    this.message = 'Component Initialized!';
  }
}

When the component loads, ngOnInit sets the message variable.


b) ngOnChanges – Detect Changes in Input Properties

The ngOnChanges lifecycle hook executes when a component receives new input data.

Example

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-child',
  template: '<p>Current Value: {{ value }}</p>',
})
export class ChildComponent implements OnChanges {
  @Input() value!: string;

  ngOnChanges(changes: SimpleChanges) {
    console.log('Previous:', changes['value'].previousValue);
    console.log('Current:', changes['value'].currentValue);
  }
}

If value changes, ngOnChanges logs the previous and current values.


c) ngDoCheck – Custom Change Detection

This hook runs after Angular’s default change detection. It is useful when tracking changes that Angular does not detect automatically.

Example

import { Component, DoCheck } from '@angular/core';

@Component({
  selector: 'app-docheck-demo',
  template: '<p>{{ counter }}</p>',
})
export class DoCheckDemoComponent implements DoCheck {
  counter = 0;

  ngDoCheck() {
    this.counter++;
  }
}

Each time Angular runs change detection, the counter increments.


d) ngOnDestroy – Cleanup Before Component Destruction

This hook is used for cleanup, such as unsubscribing from Observables or clearing intervals.

Example

import { Component, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-cleanup',
  template: '<p>Component Loaded</p>',
})
export class CleanupComponent implements OnDestroy {
  intervalId: any;

  constructor() {
    this.intervalId = setInterval(() => {
      console.log('Running background task...');
    }, 1000);
  }

  ngOnDestroy() {
    clearInterval(this.intervalId);
    console.log('Component Destroyed. Cleanup done.');
  }
}

When the component is removed from the DOM, ngOnDestroy clears the interval.


6. Using Lifecycle Hooks in a Real Application

A typical scenario where lifecycle hooks are useful:

  1. ngOnInit – Fetch initial data from an API.

  2. ngOnChanges – React to changes in user input.

  3. ngOnDestroy – Unsubscribe from API calls to prevent memory leaks.


7. Conclusion

Understanding Angular components and lifecycle hooks is essential for building efficient applications. Components define the UI and logic, while lifecycle hooks allow developers to control their behavior at different stages.

In summary, you have learned:

  • The structure of an Angular component.

  • How to create and use components.

  • The purpose of lifecycle hooks and how to implement them.

Related post

Leave a Reply

Your email address will not be published. Required fields are marked *