Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

angular reactive forms value does not get updated on using google address autocomplete

This is my HTML

<input type="text" formControlName="Address" class="form-control col-md-12 addressfield" />

for google address I used

for (i = 0; i < x.length; i++) {
  new google.maps.places.Autocomplete(document.getElementsByClassName("addressfield")[i], {types: ['geocode']});
        }

This worked fine and google address was showing options and I am able to select address.

But when I try to get the value, its only showing the text I typed

this.someForm.value.Address

For example, I typed the following and selected the first option

enter image description here

But when I tried to get the value, it was showing only the part that I typed and not the value that I selected

enter image description here

Upvotes: 0

Views: 1120

Answers (2)

Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

Here's what I did to address the issue

In the .html file, I added an Id to the element

<input type="text"  formControlName="Address" #Address class="form-control col-md-12 addressfield" />

in the component.ts I added the below code

I added ElementRef to import

import { Component, NgModule,ElementRef } from '@angular/core';

I declared value

@ViewChild('Address',{static:false}) Address: ElementRef;
//here the 'Address' should be same as the ID value (#Address) that you used in the .html

then for fetching value from the input, instead of this.someform.value.Address I used

this.Address.nativeElement.value

This had the complete address populated by the google plugin

Upvotes: 0

Vivek Doshi
Vivek Doshi

Reputation: 58593

It won't work that way,

Reason is : You are typing in your input formControl, but google address is being displayed on other elements created by google lib it self, so when you select one of the option it will set adreess to its crated element and not in your input. you need to set it up on it place_changed event.

Here is the code snippet, that might can help you:

let autocomplete = new google.maps.places.Autocomplete(document.getElementsByClassName("addressfield")[i], {types: ['geocode']});
autocomplete.addListener("place_changed", () => {
    let place = autocomplete.getPlace();
    this.YOUR_FORM_GROUP.get('Address').setValue(place.formatted_address)
});

Upvotes: 1

Related Questions