ProCodebaseProCodebase
  • ModusA Growth OS for your business, on WhatsAppKiosqSell more. Chase less.AI InterviewerAutomated screening & AI-led interviewsXperto AIAI prep companion for candidatesAI Tools HubResume builder, learning paths & more
  • Pre-Vetted DevelopersScreened, scored and ready to interviewAI-Native DevelopersSenior engineers on an hourly basis
  • Services
  • Features
  • AI Coaching
  • Jobs
  • FAQs
Sign inBook a demo
  • Services
  • Features
  • AI Coaching
  • Jobs
  • FAQs
Sign inBook a demo
ProCodebaseProCodebase

ProCodebase Technologies builds AI products for hiring and growth, and ships software for clients as a technical consultancy. We source, screen and deliver pre-vetted developers — so you only interview high-signal candidates.

Products

  • Modus
  • Kiosq
  • AI Interviewer
  • Xperto AI
  • AI Tools Hub

Hire & build

  • Pre-Vetted Developers
  • AI-Native Developers
  • Technical Consultancy
  • MVP Development
  • Features

Resources

  • Articles
  • Topics
  • Certifications
  • Collections
  • Jobs

Company

  • About Us
  • Contact Us
  • Book a Demo
  • FAQs

© 2026 ProCodebase Technologies. All rights reserved.

  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Understanding Angular Components and Their Lifecycle Hooks

author
Generated by
Kumar Palanisamy

24/10/2024

Angular

Sign in to read full article

What are Angular Components?

Angular components are the fundamental building blocks of any Angular application. A component controls a part of the user interface (UI) and plays a vital role in the architecture of Angular applications. Each component consists of three main files:

  1. HTML Template: Defines the view that the component will render.
  2. CSS Styles: Contains the styling specific to the component.
  3. TypeScript Class: Implements the logic and behavior of the component.

Creating a Simple Component

To create a component, you can use Angular CLI, a command-line interface tool that simplifies Angular development. Here’s how you can generate a new component named example:

ng generate component example

This command will create a new folder called example, containing the following files:

  • example.component.ts: The TypeScript class where the component logic is defined.
  • example.component.html: The HTML template for the component.
  • example.component.css: The stylesheet for the component.
  • example.component.spec.ts: The unit test file for the component.

Example Component Code

Here’s an illustration of what your example.component.ts could look like:

import { Component } from '@angular/core'; @Component({ selector: 'app-example', templateUrl: './example.component.html', styleUrls: ['./example.component.css'] }) export class ExampleComponent { title = 'Welcome to Angular Components!'; changeTitle() { this.title = 'Title Changed!'; } }

And your example.component.html file might look like this:

<h1>{{ title }}</h1> <button (click)="changeTitle()">Change Title</button>

In this example, clicking the button updates the title displayed in the <h1> tag.

Understanding the Component Lifecycle

Every component in Angular goes through a designated lifecycle, which consists of specific events called lifecycle hooks. These hooks allow you to tap into key points of the component’s existence, offering opportunities to perform actions during its creation, update, and destruction phases.

Key Lifecycle Hooks

Here's a breakdown of some of the most commonly used lifecycle hooks:

  1. ngOnInit(): Called once after the component is initialized. This hook is ideal for fetching data or initializing properties.
  2. ngOnChanges(): Invoked whenever any data-bound input property changes. You can use this hook to react to those changes.
  3. ngDoCheck(): Allows custom change detection. It runs after every change detection cycle in Angular.
  4. ngOnDestroy(): Triggered just before a component is destroyed. This is a good place to clean up subscriptions or detach event handlers.

Implementing Lifecycle Hooks

Here’s an example of implementing a couple of lifecycle hooks:

import { Component, OnInit, OnDestroy } from '@angular/core'; @Component({ selector: 'app-lifecycle-demo', template: ` <h2>Lifecycle Demo</h2> <p>Current count: {{ count }}</p> <button (click)="increaseCount()">Increase Count</button> ` }) export class LifecycleDemoComponent implements OnInit, OnDestroy { count: number = 0; ngOnInit() { console.log('Component initialized!', this.count); } increaseCount() { this.count++; } ngOnDestroy() { console.log('Component is about to be destroyed!'); } }

In this LifecycleDemoComponent example:

  • The ngOnInit() method logs a message when the component initializes.
  • The ngOnDestroy() method logs a message just before the component is destroyed.

Practical Use Cases

  1. Fetching Data on Initialization: Use ngOnInit() to call a service that fetches data after the component is constructed.

    ngOnInit() { this.dataService.getData().subscribe(data => { this.items = data; }); }
  2. Cleaning Up Resources: If you have a subscription to an observable, use ngOnDestroy() to unsubscribe to prevent memory leaks.

    private subscription: Subscription; ngOnInit() { this.subscription = this.dataService.data$.subscribe(data => { this.items = data; }); } ngOnDestroy() { this.subscription.unsubscribe(); }

Bonus: Using ngOnChanges

If your component has @Input properties, you can react to their changes using ngOnChanges().

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-input-demo', template: `<h3>New Title: {{ title }}</h3>` }) export class InputDemoComponent implements OnChanges { @Input() title: string; ngOnChanges(changes: SimpleChanges) { console.log('Title changed:', changes.title.currentValue); } }

In this example, ngOnChanges() allows you to react when the title input property changes, letting you know what the new value is.

Conclusion

Components form the backbone of Angular applications, and understanding their lifecycle is crucial to building efficient and maintainable applications. The lifecycle hooks provide powerful opportunities to manage the flow of data and clean up resources. Embracing these concepts will not only help you write better Angular applications but will also enhance your overall web development skills. Stay tuned for more insights as we continue our journey through Angular!

Popular tags

AngularComponentsLifecycle Hooks

Share now!

Like & bookmark

Related collections

  • Angular Mastery: From Basic to Advanced

    24/10/2024 · Angular

Related articles

  • Angular Reactive Forms and Form Validation

    24/10/2024 · Angular

  • Angular Routing and Navigation

    24/10/2024 · Angular

  • Angular CLI Setup and Project Structure

    24/10/2024 · Angular

  • Making the Most of Angular HTTP Client with RESTful APIs

    24/10/2024 · Angular

  • Understanding Angular Lazy Loading and Code Splitting

    24/10/2024 · Angular

  • Understanding Angular Services and Dependency Injection

    24/10/2024 · Angular

  • Unit Testing in Angular with Jasmine and Karma

    24/10/2024 · Angular

Popular category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design