Posts

Showing posts from May 14, 2025

Understanding ngOnChanges in Angular: Detecting Input Changes from Parent Components

Understanding ngOnChanges in Angular: Detecting Input Changes from Parent Components In Angular, the ngOnChanges lifecycle hook is a powerful tool for tracking changes to @Input() properties passed from parent to child components. It enables developers to react to data updates, reset internal state, or trigger dependent logic in response to those changes.   What Is ngOnChanges? The ngOnChanges() method is called whenever an @Input() property changes. It receives a SimpleChanges object that contains the previous and current values of all bound properties that have changed.   When to Use ngOnChanges Here are 5 common use cases for ngOnChanges:   1. Reacting to Input Property Changes When a child component receives new input and needs to perform actions like fetching related data.   @Input() userId: number;   ngOnChanges(changes: SimpleChanges) {   if (changes['userId']) {     this.loadUserData(this.user...

Dynamic Country and State Dropdowns in Angular using Web API

Dynamic Country and State Dropdowns in Angular using Web API When building modern web applications, especially employee forms or address inputs, it's common to let users select their country and state from a dynamic list. Instead of hardcoding these options, we’ll make them dynamic by fetching them from a backend API. In this tutorial, we’ll walk through how to create an employee form in Angular that: Loads countries from a backend API on initialization. Loads states based on the selected country. Submits the complete form data.   Backend API Structure For this example, we'll assume an ASP.NET Web API with the following endpoints: GET /api/countries         // Returns a list of countries GET /api/states?countryId=1  // Returns states for a specific country   Each country/state might look like: // Country { "id": 1, "name": "United States" }   // State { "id": 101, "n...