Google 放置指令未更新 angular 中的表单控件值 2

Google place directive not updating form control value in angular 2

我有一个 google 放置指令;当我在输入字段中键入时,它会建议地点,而在 selection 上,它会输出地名。我在输入字段中看到 selected 值,但我的表单控件值仅显示我在输入字段中键入的内容。我正在使用模型驱动形式。例如:如果我输入 bha,然后输入 select Bharat Diamond House,输入字段会正确显示 Bharat Diamond House 但表格值只得到 bha。我的问题类似于 and this

我的指令是这样的:

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

不熟悉 Google 地方,但我可以告诉你很多,这些变化不受影响,因为你需要在这里使用 patchValue,并修补你从指令中获得的值.

HOW 你这样做,你需要弄清楚,可能需要从你的指令中添加 EventEmitter,即 returns 你的价值,然后你可以像下面这样修补它:

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

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

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

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

以及何时需要检测更改:

this.ref.detectChanges();

这是我在测试你的 plunker 时注意到的,它是必需的。这是您的Plunker,我在那里做了一个极差的解决方案。但我想测试它,在这里我手动分配你从指令中获得的值 venue_name (仅),以展示该字段上的 patchValue