Angular - Google places directive isn't being

2019-05-25 08:06发布

问题:

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