Angular-输入值更改时不会触发Google Places指令 [英] Angular - Google places directive isn't being triggered when the input value changes

查看:83
本文介绍了Angular-输入值更改时不会触发Google Places指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写google place指令,因为所有完成的指令似乎都无法很好地工作或具有可怕的代码库.

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

然后我这样使用:

<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?

推荐答案

当Google Map事件在角度区域外触发时,您需要在角度区域内运行回调:

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

另请参见

这篇关于Angular-输入值更改时不会触发Google Places指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆