This is my html file, where I want that when a user fills the PIN CODE, the rest of the addresses like DISTRICT, STATE and CITY should be auto filled using the API data.
The API is: https://api.postalpincode.in/pincode/244713
<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 is 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);
});
}
Here I was trying to store the API details in finalAddress variable, but even if I write {{finalAddress.Message}} it gives me an error. If someone have a solution please help me.
You are in the right direction. You need to modify your code slightly :
You need to add
[(ngModel)]
to each of the input fields you want to populate the values. then assign them to the variables. The API returns multiple objects of address so you need to pick one (I picked first).Update your code :
add these variables in the component :
then in html assign it to the respective input field :
update the add method as :
Here is the working Demo