Google Place指令不以角度2更新表单控件值

时间:2017-03-18 12:48:41

标签: forms angular google-places-api angular2-directives

我有一个google place指令;当我输入我的输入字段时,它会显示位置,并在选择时输出地名。我在输入字段中看到所选的值,但我的表单控件值仅显示我在输入字段中输入的内容。我正在使用模型驱动的形式。例如:如果我输入 bha 然后选择 Bh​​arat Diamond House ,则输入字段会正确显示 Bh​​arat Diamond House ,但表单值只能 BHA 即可。我的问题类似于thisthis

我的指示如下:

import {Directive, ElementRef, EventEmitter, Output} from '@angular/core';
import {NgModel} from '@angular/forms';
import {Address} from './model/google_place';

declare var google:any;

@Directive({
  selector: '[googleplace]',
  providers: [NgModel],
  host: {
    '(input)' : 'onInputChange($event)'
  }
})
export class GoogleplaceDirective  {
  @Output() setAddress: EventEmitter<any> = new EventEmitter();
  @Output() adr_address: EventEmitter<any>  = new EventEmitter();
  @Output() place_id: EventEmitter<any>  = new EventEmitter();
  @Output() formatted_address: EventEmitter<any>  = new EventEmitter();

  modelValue:any;
  autocomplete:any;
  private _el:HTMLElement;
  place:Address;

  constructor(el: ElementRef, private model:NgModel) {
    this._el = el.nativeElement;
    this.modelValue = this.model;
    var input = this._el;
    this.autocomplete = new google.maps.places.Autocomplete(input, {});
    google.maps.event.addListener(this.autocomplete, 'place_changed', ()=> {

      (<HTMLInputElement>input).value=(<HTMLInputElement>input).value.split(',')[0];

      this.place = this.autocomplete.getPlace();
      if (this.place && this.place.place_id){
        this.invokeEvent();
      }
    });
  }

  //invokeEvent(place:Object) {
  invokeEvent() {
    this.setAddress.emit(this.place);
    this.adr_address.emit(this.place.adr_address ? this.place.adr_address : null);
    this.formatted_address.emit(this.place.formatted_address ? (this.place.formatted_address) : null);
  }

  onInputChange() {

  }
}

PLUNK

1 个答案:

答案 0 :(得分:1)

不熟悉Google地方,但我可以告诉您更改不会受到影响,因为您需要在此使用patchValue,并修补从指令中获得的值。

如何 你这样做,你需要弄清楚,可能需要从你的指令添加EventEmitter,它返回你的值,然后你可以修补像以下内容:

this.createEventForm.patchValue({venue_name: theValue}) 

正如我之前从问题中注意到的那样,Google地图/地方似乎存在更改检测问题,因此您可能需要使用ChangeDetectorRef

import { ChangeDetectorRef} from '@angular/core';

constructor(public createEventFb:FormBuilder, private ref: ChangeDetectorRef) { }

当您需要检测更改时:

this.ref.detectChanges();

当我测试你的羽毛球时,我注意到这是需要的。这是您的Plunker,我在其中执行了 非常差的 解决方案。但是我想测试一下,在这里我手动分配你在venue_name(仅限)的指令中获得的值,以在该字段上展示patchValue