【问题标题】:ngModel of textBox doesn't hold the correct value when using Google Places Autocomplete API使用 Google Places Autocomplete API 时 textBox 的 ngModel 的值不正确
【发布时间】:2016-10-04 12:15:49
【问题描述】:

我想使用带有 textField 的 Google Places Autocomplete API,以便在我输入内容时可以看到城市建议。我的 textField 使用 ngModel 绑定到变量“searchFieldValue”。 如果我在文本框中键入内容,此变量将保持正确的值。但是,如果我开始输入,然后从 Google 自动完成中选择某些内容,“searchFieldValue”将不会更新为所选内容 - 它只包含我输入的部分。 例子: 我输入:“Washi”,然后从 Google API 提供的建议城市中选择“Washington, USA”。虽然在文本字段中有“美国华盛顿”,但我的变量“searchFieldValue”只有“Washi”。我希望这个变量包含与文本字段中相同的数据,即“美国华盛顿”。

我该怎么做?

这是我的组件:

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

}

【问题讨论】:

    标签: angular typescript google-places-api angular2-ngmodel


    【解决方案1】:

    在 autoCompleteSearchBoxInit 中你可以添加下面的,你可以处理它。

    google.maps.event.addListener(autocomplete, 'place_changed', () => {
        this.zone.run(() => {
            var  place = autocomplete.getPlace();
            //handle your logic using place variable
        });
    });
    

    【讨论】:

    • 非常好的解决方案,我不知道你是怎么知道的
    猜你喜欢
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 2016-08-15
    • 2018-11-09
    • 2017-01-23
    • 2023-01-21
    相关资源
    最近更新 更多