I am trying to implement the Google Places Autocomplete API with a textField in my project. The goal is to have city suggestions appear as I type in the textField. Currently, I have bound my textField to a variable called "searchFieldValue" using ngModel. The issue I am facing is that although the variable holds the correct value when I manually type something into the textField, it does not update when I select a suggestion from the Google Autocomplete dropdown. For example, if I type "Washi" and then choose "Washington, USA" from the suggestions provided by Google API, the textField displays "Washington, USA" but the variable "searchFieldValue" still contains "Washi". I want the variable to reflect the selected value from the textField, which in this case should be "Washington, USA".
Any ideas on how to achieve this?
Here's the component code snippet:
import { Component, OnInit } from '@angular/core';
import { WeatherAPIService } from './weatherAPI.service';
declare var google: any; //for Places Autocomplete API
@Component({
selector: 'my-cities-search',
template: `
<input class="form-control input-lg" #box id="searchTextField" (keyup.enter)="searchBoxChanged()"
(blur)="searchBoxChanged()" [(ngModel)] = "searchFieldValue">
`,
styleUrls: [ 'app/cities-search.component.css' ],
})
export class CitiesSearchComponent implements OnInit {
constructor(
private weatherAPIService: WeatherAPIService
) { }
//content of searchbox field
searchFieldValue: string = "";
autoCompleteSearchBoxInit() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}
searchBoxChanged () {
console.log(this.searchFieldValue)
if (this.searchFieldValue != "")
this.weatherAPIService.cityName = this.searchFieldValue;
}
ngOnInit(): void {
this.autoCompleteSearchBoxInit();
}
}