How can I enable the feature of automatic address population when entering a PIN CODE in an Angular application?

I have created an HTML file where I aim to automatically fill in the DISTRICT, STATE, and CITY fields once a user enters the PIN CODE. The data will be fetched using an API.

The API link is:

<div class="cardParts5">
                <div class="cardTitle">
                    Communication Address
                </div>

                <div class="addressContainer">
                  
                    <div class="field1">
                        <mat-form-field class="example-full-width" appearance="fill" class="mat-form">
                            <mat-label>Pin Code*</mat-label>
                            <input matInput maxlength="6" [(ngModel)]="pinCode" name="pinCode">
                            <button (click)="getAdd(pinCode)">home</button>
                        </mat-form-field>
                    </div>

                    <div class="field2">
                        <mat-form-field class="example-full-width" appearance="fill" class="mat-form">
                            <mat-label>State*</mat-label>
                            <input matInput>
                        </mat-form-field>
                    </div>

                    <div class="field3">
                        <mat-form-field class="example-full-width" appearance="fill" class="mat-form">
                            <mat-label>District*</mat-label>
                            <input matInput>
                        </mat-form-field>
                    </div>

                    <div class="field4">
                        <mat-form-field class="example-full-width" appearance="fill" class="mat-form">
                            <mat-label>City/Village*</mat-label>
                            <input matInput>
                        </mat-form-field>
                    </div>
                </div>
            </div>

This snippet of code belongs in my component.ts file:



import { Component, OnInit, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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



export class FinalPayComponent implements OnInit {
  pinDetails:any;
  finalAddress:any;
  public pinCode = '';

  constructor( private httpClient: HttpClient ) { }

  ngOnInit(): void { }
  
  getAdd(pinCode){
      this.http.get(`https://api.postalpincode.in/pincode/${pinCode}`).subscribe((val)=>{
        this.pinDetails = JSON.stringify(val);
        this.finalAddress = JSON.parse(this.pinDetails);
        console.log(this.finalAddress);
    });
  }

If you have any insights on how to resolve the issue of handling the API response in the finalAddress variable, please provide your guidance. Thank you!

Answer №1

You are on the right track. Your code just needs a slight adjustment:

To populate the values in the input fields, you need to add [(ngModel)] to each of them and then assign them to variables. Since the API returns multiple address objects, you will need to pick one (I chose the first one).

Make the following updates to your code:

Include these variables in the component:

  public state = '';
  public block = '';
  public district = '';
  public city = '';

Then, in the HTML, assign them to the corresponding input fields:

<input matInput [(ngModel)]="state" />

Update the add method as follows:

getAdd(pinCode) {
    this.httpClient
      .get(`https://api.postalpincode.in/pincode/${pinCode}`)
      .subscribe((val) => {
        const [address] = val as any;
        this.finalAddress = address;
        console.log(this.finalAddress); // it returns multiple postOffices
        const postOffices = this.finalAddress.PostOffice;
        if (postOffices.length > 0) {
          this.state = postOffices[0].State;
          this.district = postOffices[0].District;
          this.city = postOffices[0].Name;
        }
      });
  }  

Check out the live Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting: Unable to mutate a state variable in Vuex

I am working on updating my contact list whenever a different brand is selected. The goal is to clear the array of contacts associated with the current brand and then refill it with the new brand's contacts. However, I'm facing an issue in my Vu ...

What is the process for dynamically altering the source file of VueRouter?

Hello, I am working on a project that involves multiple roles using VueJs and Laravel. Laravel is used as the back-end while Vuejs serves as the front-end. The project has three different roles: User, Modirator, and Editor. Here is a snippet of my code ...

Obtain the coordinates of the pixel in an image on the canvas when a mouse

I am currently working on a project that involves using canvas. I have set a picture as the background of the canvas and would like to be able to get the original pixel point when clicking in the image area. In order to achieve this, I need to convert canv ...

Managing a click event with an element in React using TypeScript

Hey there, I'm pretty new to TypeScript and React. I have this event where I need to identify the element that triggered it so I can move another element close to it on the page. However, I'm facing some challenges trying to make it work in React ...

Using JavaScript to generate dynamic folders in Alfresco is not functioning as expected

Working with Alfresco 4.0.d community edition (also tested on Alfresco 4.0.c) on an Oracle Linux 64-bit virtual machine using Firefox. I've been developing a script to dynamically create sub-folders as new items are added to a space/folder via a rule ...

Navigating JSON Objects in Ionic 2

Example of my JSON array structure [{ label: "Interests", datatype: "check", lookupname: "null", order: "05", options: [ 0:{id: "01", value: "Photography"} 1:{id: "0 ...

What is preventing me from utilizing my JavaScript constructor function externally?

I have a question about how I create my object: var myViewModel = new MyViewModel("other"); Why am I unable to call myViewModel.setHasOne(value) from outside the viewmodel? Whenever I try, I encounter this error message: Uncaught TypeError: Cannot ca ...

Dealing with an endless loop in an external JavaScript file (C# .NET)

Looking for a way to safely load a third-party script file that might contain an infinite loop without hanging the page? I attempted to call the javascript file within an updatepanel on button click, but encountered issues with the page still freezing. Eve ...

Fine Uploader angularjs directive malfunction detected

I have been trying to integrate a file upload library for IE9 (although I have tested it on all browsers), but I am encountering an error that I cannot seem to resolve. TypeError: element.getElementsByTagName is not a function (line 134) candidates = elem ...

Tips for utilizing Express.js Request and Response as parameter types in JSDoc

One of my functions requires Express Request and Response objects as arguments. function doSomething(request, response) { // perform actions } Is there a way to utilize jsdoc to specify the types of request and response? UPDATE: I believe this questio ...

Utilize systemJs to import a node module in a TypeScript file

I attempted to import a node module called immutablejs into my TypeScript file: /// <reference path="../node_modules/immutable/dist/immutable.d.ts" /> import { Map } from 'immutable'; var myMap = Map(); Here are the script tags in my inde ...

MUI-Datatable rows that can be expanded

I'm attempting to implement nested tables where each row in the main table expands to display a sub-table with specific data when clicked. I've been following the official documentation, but so far without success. Below is a code snippet that I& ...

Reorganize divisions using Bootstrap

I am exploring different ways to manage responsiveness through the reordering of divs. While I am aiming for a solution that is highly flexible, any suggestion would be appreciated. Desktop View: https://i.stack.imgur.com/boSOa.png Mobile View: https:// ...

Error message: After using gulp-npm-dist to copy only the dependency modules, the node module was not

I'm currently exploring different methods to package only the necessary node_modules dependencies for my project. After some research, I came across gulp-npm-dist and created a gulpfile.js. var gulp = require('gulp'); var npmDist = requir ...

Angular - Displaying Date in Proper Format

Looking for a solution to format a date object from a Java backend using Angular or JS without any plugins? Here's my dilemma: the Java backend only accepts a string and later parses it into a date object. In my current Angular code, I'm trying: ...

Having trouble with Vue image source file paths?

Having an issue with loading an image via file_path on Vue. When using a hardcoded path, it works fine. Refer to the sample code below: JavaScript function getRestaurantsbyId(id) { var restaurants = { "1" : { "name": "xxxx", ...

Guide to sending a HTTP POST request with parameters in typescript

I need assistance sending a POST request using parameters in the following format: http://127.0.0.1:9000/api?command={"command":"value","params":{"key":"value","key":"value","key":"value","key":value,}} I attempted to do this but encountered an issue: l ...

Guide to iterating through different endpoints in a predetermined sequence

I am facing a challenge with testing various endpoints using different login credentials. When looping through the endpoints, the results are not appearing in the sequential order due to asynchronous nature. My goal is to iterate through each endpoint wit ...

Using TypeScript with react-chart-js-2 to create LineCharts: Uncaught Error - Element "point" is not registered

I am currently facing an issue while trying to create a LineChart using react-chartjs-2 with TypeScript. The implementation seems error-free and the website renders correctly. However, when I attempt to access the component responsible for rendering the Li ...

Creating dynamic form groups that allow for the addition and removal of forms while assigning unique identifiers and names to each input field

I am currently immersed in the development of a sophisticated CMS system. My main objective is to dynamically add and remove form inputs using JavaScript upon clicking a button, with the ultimate goal of submitting the data into a database via PHP script. ...