Angular - Google places directive isn't being triggered when the input value changes

喜夏-厌秋 提交于 2019-12-10 11:24:57

问题


I'm trying to write a google place directive since all the finished ones doesn't seem to work very well or have a code base that is just horrendous.

So here is my attempt which is clean but it isn't activating when the user types something:

@Directive({
  selector: '[googlePlace]'
})

export class GoogleplaceDirective implements OnInit {
  @Output() placeChange: EventEmitter<any> = new EventEmitter<any>();

  public autocomplete: any;

  constructor(private elementRef: ElementRef) {}

  ngOnInit() {

    this.autocomplete = new google.maps.places.Autocomplete(this.elementRef.nativeElement, {});

    google.maps.event.addListener(this.autocomplete, 'place_changed', () => {

      const place = this.autocomplete.getPlace();

      this.placeChange.emit(place);
    });
  }
}

Which I then use like this:

<input formControlName="address" googlePlace (placeChange)="setAddress($event)">

But when I type in the input the autocomplete is not triggering, I'm probably missing something simple but I cannot figure out what that could be. Maybe I have to listen to the input manually somehow and then trigger a search?


回答1:


As google map events are fired outside angular zone you need to run callback inside angular zone:

constructor(private zone: NgZone) {}

google.maps.event.addListener(this.autocomplete, 'place_changed', () => {
  const place = this.autocomplete.getPlace();
  this.zone.run(() => this.placeChange.emit(place)); // run inside angular zone
});

See also

  • google maps places autocomplete addEventListener doesn't work


来源:https://stackoverflow.com/questions/43910707/angular-google-places-directive-isnt-being-triggered-when-the-input-value-cha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!