使用Google商家信息自动填充API时,textBox的ngModel不具有正确的值

时间:2016-10-04 12:15:49

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

我想将Google商家信息自动填充API与textField结合使用,以便在输入内容时可以看到城市的提案。我的textField使用ngModel绑定到变量“searchFieldValue”。 如果我在textBox中输入内容,则此变量保存正确的值。但是,如果我开始输入,然后从Google自动填充中选择一些内容,则“searchFieldValue”将不会更新为所选内容 - 它只保留我输入的部分。 例: 我键入:“Washi”,然后我从Google API提供的拟议城市中选择“华盛顿,美国”。虽然在文本区域有“华盛顿,美国”,但我的变量“searchFieldValue”只有“Washi”。我希望这个变量包含与textfield中相同的数据,即“Washington,USA”。

我该怎么做?

这是我的组件:

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

}

1 个答案:

答案 0 :(得分:3)

在autoCompleteSearchBoxInit中,您可以添加以下内容,然后就可以处理它了。

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