Search code examples
google-mapsangulareventemitter

Autocomplete dropdown input selection not triggering ngModelChange


When I choose a google maps address autocompleted result from the dropdown, it doesn't pass to my parent component, but it does when I manually enter the address.

I'll start typing, and it's passing the info, and once I select an address it fills in the rest for me, but doesn't pass that data, even though it's showing in the input box.

I'm using this input (in the child template) to get addresses with a google map div:

<input
  [(ngModel)]="address"
  (ngModelChange)="addressChange.emit($event)"
  id="pac-input"
  name='address'
  class="mapControls"
  type="text"
  placeholder="Enter Address"
>

in my child component:

@Component({
  selector: 'gmap',
})

export class gMap{
  @Input() address;
  @Output() addressChange = new EventEmitter();
}

in my parent template:

<gmap [(address)]="address"></gmap>

and parent component:

address: string;

Obviously there's more code, but this is the important stuff I think. Anyone know how to make it so when I select an autocomplete result from the dropdown it triggers ngModelChange with the data chosen from the selection?


Solution

  • I sort of fixed it, I did this:

    So since we're using typescript I changed google's all of

    function()
    

    to

    () =>
    

    then, under these functions of the google map code

    searchBox.addListener('place_changed', () => {
        places.forEach((place) => {
    

    I called the emitter

    this.addressChange.emit(place.formatted_address);
    

    there's a huge delay, sometimes like 20 seconds, but it works!

    Anyone know why there's a few-second delay between when I choose from the drop-down and the emitter goes off? I'd really like to remove that delay

    If you use promise object then the response will be very fast.

    return new Promise((resolve, reject) =>{
      autocomplete.addListener('place_changed', () => {
         var place = autocomplete.getPlace();
         console.log("place "+place);
        resolve(place);
      });
    })