问题描述
我正在尝试编写一个 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 事件在 angular zone 外触发时,您需要在 angular zone 内运行回调:
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 放置指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!