The ngModel for a text box does not store the accurate value when the Google Places Autocomplete API is being utilized

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();
  }

}

Answer №1

Within autoCompleteSearchBoxInit, you have the opportunity to include the following code snippet and manage it accordingly.

google.maps.event.addListener(autocomplete, 'place_changed', () => {
    this.zone.run(() => {
        var place = autocomplete.getPlace();
        // Perform your operations based on the 'place' variable
    });
});

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

Preventing specific directories from being imported in a Typescript project

I am intrigued by the idea of restricting files within a specific scope from importing files from another scope. Let's consider this example: Imagine we have the following project structure: project/ ├── node_modules/ ├── test/ ├── ...

Apply a class using [ngClass] based on an HTML condition within the local scope

In the past, I have utilized [ngClass] to assign classes based on the Boolean value of a variable in the JavaScript/TypeScript. However, I am now curious if it is achievable to apply [ngClass] based on a local HTML boolean value instead? For example: < ...

The build process is currently being executed by another process with the ID of xxx. Please try again later

In my Nx monorepo, I have 2 projects. Building these projects locally works fine, but when trying to build them on the server, I encounter an error: Another process, with id 111, is currently running ngcc. Waiting up to 250s for it to finish. (If you are s ...

Tips for selecting the correct type for an array of Unions with the help of Array.prototype.find

I have the following variations: type First = { kind: 'First', name: string } type Second = { kind: 'Second', title: string } type Combo = First | Second; I am attempting to locate the element of type First in a Combo[], as shown bel ...

The parameter type '{ src: string; thumb: string; }' cannot be assigned to the 'never' type in the argument

Sample Typescript Code: I am experiencing issues with my code and cannot comprehend this error message- Argument of type '{ src: string; thumb: string; }' is not assignable to parameter of type 'never' _albums = []; constructor( ...

How can I efficiently make a dropdown menu with search functionality instead of using datalist?

I am currently working on creating a custom searchable input field that makes backend calls. Instead of using datalist, I want to design a unique UI with ul and li items. While I have successfully implemented the search functionality, I am facing a glitc ...

Is it possible to have an optional final element in an array?

Is there a more graceful way to declare a Typescript array type where the last element is optional? const example = (arr: [string, string, any | undefined]) => console.log(arr) example(['foo', 'bar']) When I call the example(...) f ...

Tips for running a function before initializing Angular 2

Is there a way to run a function before initializing Angular in the current ng2 CLI configuration? One approach is to use SystemJS and call System.import() immediately after our function executes. ...

Using TypeScript with knockout for custom binding efforts

I am in the process of developing a TypeScript class that will handle all bindings using Knockout's mechanisms. Although I have made progress with the initial steps, I have encountered a roadblock. While I can successfully bind data to my HTML element ...

What is the process for a component to wait for a subscription in Angular

Encountering an issue with initializing an autocomplete for Users on initial load. This snippet shows the UsersService implementation: public users: User[] = []; constructor(private http: HttpClient) { this.http.get<User[]>(environment.apiUrl + ...

Obtaining the host and port information from a mongoose Connection

Currently, I am utilizing mongoose v5.7.1 to connect to MongoDb in NodeJS and I need to retrieve the host and port of the Connection. However, TypeScript is throwing an error stating "Property 'host' does not exist on type 'Connection'. ...

The Angular client fails to receive data when the SignalR Core Hub method is called from the Controller

Issue with Angular SignalR Client not Receiving Data from ASP.NET API I have a setup where an angular website is connected to an asp.net back-end using SignalR for real-time data service. Everything was working fine when tested in localhost, but after pub ...

The ElementRef was modified following the activation of a click event

Let me explain my current situation: I am working with 3 components: MainComponent, ComponentA, and ComponentB. MainComponent dynamically loads ComponentA. ComponentA contains a button that, when clicked, calls MainComponent.addComponent(ComponentB). exp ...

Troubleshooting issue with Ionic FilePath: How to retrieve file path in Android 11

Recently, I've been looking into the changes in the Android file system due to the release of Android 11. Currently, I am encountering an issue with opening a file using the Android File Chooser from within my Ionic app. https://ionicframework.com/do ...

Uh-oh! Looks like there was an issue trying to read properties of something that doesn't exist

I have a Spring Boot-Angular application and I am implementing server-side pagination. While my application is working fine, I am encountering a console error in TypeScript. Here is the code from user-list.component.ts: userList(): void{ this.userServ ...

Designing a user interface for unlimited nested components with optional properties

I am currently working on creating an interface for the specific object type shown below. "Condition": { "And": { "Or": { "userData": [ { "name": "Alex", &q ...

Create a streaming service that allows for multicasting without prematurely ending the main subject

In my implementation of caching, I am utilizing BehaviorSubject and multicast. The cache stream should begin with an HTTP request and I want the ability to manually trigger a cache refresh by calling next on the subject. While the conventional method of us ...

Leveraging TypeScript modules without the need for require()

I created a TypeScript 2.3 app called app.ts that requires the Vue.js library version 2. I manually added the Vue.js script src in the HTML file. All I wanted was to use Vue.js with type checking. I thought I could simply reference it like this: /// & ...

Issue occurred with Firebase geoFire setting: unable to access properties of undefined when reading 'pieceNum_'

Recently, I decided to update my old Ionic Angular app and upgraded the firebase module to version 9.23.0 along with the geofire module to version 6.0.0. However, upon calling the set function on geoFire with an id and an array of coordinates, I encountere ...

The parameter type 'OperatorFunction<User, void>' cannot be assigned to the parameter type 'OperatorFunction<Object, void>'

Hey there, I'm currently diving into Angular and trying to figure out how to work with API's. However, I've encountered a bit of a roadblock in my code when attempting to retrieve data from the key. Argument of type 'OperatorFunction&l ...