Skip to content
codeaihub.in
Menu
Menu

Chapter 1.1 Modules & Components in Angular – NgModules & Component Lifecycle Hooks

Posted on February 24, 2025February 24, 2025 by Tech Writer

Introduction

Angular is a popular front-end framework that follows a modular architecture. Two core building blocks of an Angular application are Modules (NgModules) and Components. Understanding these concepts is crucial for developing scalable and maintainable applications.


What Are Angular Modules (NgModules)?

Angular applications are divided into modules to enhance maintainability and reusability.

Key Features of NgModules:

  1. Encapsulation – Keeps components, directives, and services organized.
  2. Reusability – Allows feature modules to be reused in different parts of the application.
  3. Lazy Loading – Improves performance by loading modules only when required.

Structure of an Angular Module

Every Angular application has at least one module, the root module (AppModule).

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent], // Declare components, directives, pipes
  imports: [BrowserModule], // Import other modules
  providers: [], // Register services
  bootstrap: [AppComponent] // Root component
})
export class AppModule {}

Types of Angular Modules:

  1. Root Module – Bootstraps the application (AppModule).
  2. Feature Modules – Encapsulates specific functionality (e.g., UserModule, ProductModule).
  3. Shared Module – Contains reusable components, pipes, and directives.
  4. Core Module – Manages singleton services and application-wide functionalities.

What Are Angular Components?

Components are the UI building blocks in Angular applications. Each component consists of:

  1. Template (.html) – Defines the structure and layout.
  2. Styles (.css or .scss) – Controls the appearance.
  3. Class (.ts) – Contains logic and data binding.

Structure 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: string = 'Hello Angular';
}

Angular Component Lifecycle Hooks

Angular provides lifecycle hooks that allow developers to execute code at specific stages of a component’s life.

List of Lifecycle Hooks:

Lifecycle HookPurpose
ngOnInit()Called after component initialization
ngOnChanges()Called when input properties change
ngDoCheck()Detects changes manually
ngAfterContentInit()Runs after content projection (ng-content)
ngAfterContentChecked()Runs after projected content changes
ngAfterViewInit()Executes after view initialization
ngAfterViewChecked()Runs after the component view updates
ngOnDestroy()Called before component destruction

Example Usage of Lifecycle Hooks

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

@Component({
  selector: 'app-lifecycle',
  template: `<h1>Lifecycle Example</h1>`
})
export class LifecycleComponent implements OnInit, OnDestroy {
  constructor() {
    console.log('Constructor called');
  }

  ngOnInit() {
    console.log('ngOnInit called');
  }

  ngOnDestroy() {
    console.log('ngOnDestroy called');
  }
}

Angular Interview Questions & Answers

Q1. What is the purpose of NgModules in Angular?

Answer: NgModules help organize an Angular application by encapsulating components, directives, pipes, and services. They promote modularity and allow features to be lazy-loaded, improving performance.

Q2. What are the different types of Angular modules?

Answer: The main types of modules in Angular are:

  1. Root Module (AppModule) – The entry point of the application.
  2. Feature Modules – Specific to a functionality (e.g., UserModule).
  3. Shared Module – Contains reusable components and directives.
  4. Core Module – Manages singleton services and global functionalities.

Q3. What is the role of a Component in Angular?

Answer: A component controls a section of the UI and consists of:

  • A template for rendering the view.
  • A class containing logic and data.
  • Styles for appearance.

Q4. What are Angular lifecycle hooks?

Answer: Lifecycle hooks allow developers to run logic at different stages of a component’s life cycle. Examples include ngOnInit() (runs after component initialization) and ngOnDestroy() (runs before component destruction).

Q5. What is the difference between ngOnInit() and constructor()?

Answer:

  • The constructor is called when the component instance is created.
  • ngOnInit() is called after the constructor and is used for initialization logic that relies on input properties.

Q6. What is Lazy Loading in Angular?

Answer: Lazy Loading is a technique where feature modules are loaded on demand instead of at the application’s startup, improving performance.

Q7. What is the difference between ngOnChanges() and ngDoCheck()?

Answer:

  • ngOnChanges() runs when an input property changes.
  • ngDoCheck() runs on every change detection cycle and allows manual change detection.

Q8. When should ngAfterViewInit() be used?

Answer: ngAfterViewInit() is used when you need to manipulate or interact with the component’s view after it has been initialized.


Conclusion

Understanding NgModules, Components, and Lifecycle Hooks is crucial for mastering Angular. These concepts ensure code modularity, reusability, and efficient application performance. For interviews, be prepared to explain their use cases and provide real-world examples.

Need more Angular tips? Stay tuned for our next blog! 🚀

Category: Angular, javascript, web development

Leave a Reply Cancel reply

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

Recent Posts

  • Agent2Agent (A2A): A New Way for AI Helpers to Work Together
  • 🤖What is a Kubernetes Cluster? A Beginner-Friendly Guide for GKE Users
  • CASA Ratio: Meaning, Formula, Importance & Impact on Banks
  • Liquidity Coverage Ratio (LCR): Importance, Formula & Impact on Banks
  • Deposit Growth in Banking: Trends, Formula, Impact & Key Drivers

Recent Comments

No comments to show.
© 2025 codeaihub.in | Powered by Minimalist Blog WordPress Theme