Angular  

Understanding Angular Lifecycle Hooks

Angular

Angular is a TypeScript-based open-source frontend framework created by Google. It helps developers build modern, scalable web apps, especially Single Page Applications (SPAs)—where the page doesn't reload, but content updates dynamically. It organizes our code using components and services, making development efficient and maintainable. Before lifecycle hooks make any sense, we’ve got to lay a solid foundation on what Angular is, how its structure works, and where components fit into the puzzle.

AngularJS vs Angular (Modern Angular)

Feature AngularJS Angular (2+)
Language JavaScript TypeScript
Architecture MVC Component-based
Mobile Support Poor Excellent
Performance Slower Faster (AOT, Tree Shaking)
Development Support Discontinued Actively maintained
Ecosystem Classic JS ecosystem RxJS, TypeScript, CLI

Here’s how the high-level angular structure looks.

Angular Element Purpose School App Example
Modules Organize the app into functional areas StudentModule, TeacherModule, AdminModule, and TimetableModule group features into manageable sections.
Components Handle UI and logic for individual features StudentListComponent, AttendanceFormComponent, and ExamResultsComponent power the core screens of the app.
Templates Define the view using Angular-enhanced HTML A dynamic report card template uses *ngFor to loop through subjects and display student scores.
Services Share business logic and data access across components StudentService centralizes logic to fetch, add, or update student records from the backend.
Routing Enable navigation between pages Angular Router handles navigation to /students, /teachers, /results, and /library.
Directives Add dynamic behavior to templates *ngIf="isAbsent" highlights students in red if they’re absent during the attendance check.
Pipes Format output in templates {{ dateOfBirth | date:'longDate' }} formats a birthday date

What is a Component in Angular?

A component in Angular is the heart of the user interface. Each screen, button, form, or card is typically implemented as a component, similar to components in .NET under the Common Language Runtime (CLR). In Angular, a component is the basic building block of the user interface (UI). It controls a part of the screen called a view, and it contains the logic (TypeScript), template (HTML), and styles (CSS) for that part.

Structure of a Component

1. Class contains the logic and data for the component using TypeScript. And File Extension: .ts

@Component({
  selector: 'app-product',         // We can use <app-product></app-product> in HTML
  templateUrl: './product.html',   // Uses product.html for UI
  styleUrls: ['./product.css']     // Uses product.css for styles
})
export class ProductComponent {    // This class holds logic like product name, price, etc.
  name = 'T-Shirt';
  price = 499;
}

2. Template defines the user interface (UI layout) using HTML. It displays data from the class using Angular's data binding.File Extension: .html

<!-- product.component.html -->
<h2>{{ productName }}</h2>
<p>Price: ₹{{ price }}</p>

3. Style adds styling (colors, fonts, spacing) specific to this component. File Extension: .css or .scss

/* product.component.css */
h2 {
  color: blue;
  font-weight: bold;
}

p {
  font-size: 16px;
}

Why are components important for Lifecycle Hooks?

Lifecycle hooks are embedded within components. So, unless you understand how components are created, rendered, and destroyed, lifecycle hooks won’t mean much. Here’s the flow.

  1. Angular initializes a component.
  2. Angular runs specific hooks at each stage of that component's life.
  3. We use those hooks to run our own logic at the perfect moment (like fetching data, unsubscribing, or calculating total).

Angular Lifecycle Hooks

Lifecycle hooks in Angular are special methods that get called automatically at specific stages of a component’s life, from creation to destruction. Lifecycle hooks let Angular manage the creation, change detection, and destruction of components. This gives us fine control over how and when code runs.

Lifecycle hooks are built-in functions that Angular calls at different moments during a component’s lifetime, like when it's created, updated, or destroyed.

Why Use Lifecycle Hooks?

We use lifecycle hooks to,

  • Run initial setup code (like fetching data when the component loads)
  • Detect changes in inputs
  • Perform cleanup tasks (like clearing timers or unsubscribing from services)
  • Debug the flow of your component.

Angular Lifecycle

Hook Name When Called Purpose Usage Example
constructor() When a component instance is created Basic initialization of class members (no Angular bindings yet) console.log('Constructor')
ngOnChanges(changes: SimpleChanges) When @Input() property changes Respond to input property changes this.loadData(changes['userId'].currentValue);
ngOnInit() Once after the first ngOnChanges() Fetch data, initialize bindings this.getDataFromService();
ngDoCheck() Every change detection run Custom change tracking logic detectManualChange();
ngAfterContentInit() After content projected via <ng-content> is initialized Set up logic dependent on projected content console.log('ng-content loaded')
ngAfterContentChecked() After every check of the content projection Respond to changes in projected content validateProjectedTemplate();
ngAfterViewInit() After the component’s view (and child views) are initialized DOM access, @ViewChild operations this.chart.init(this.chartElement.nativeElement);
ngAfterViewChecked() After every check of the component and child views Update logic if template data changes adjustLayout();
ngOnDestroy() Just before Angular destroys the component Cleanup (unsubscribe, clear interval) subscription.unsubscribe();

Conclusion

Understanding Angular’s architecture is essential for building modern, scalable, and maintainable web applications. This article walked through the foundational blocks of Angular, Components, Component Lifecycle Hooks, which provide precise control over how Angular creates, updates, and destroys components.