【发布时间】:2018-02-01 00:46:20
【问题描述】:
我想使用 Angular 2 Google 地图自动完成功能,我找到了this directive。
当我尝试使用它时,它给了我这个错误:
errors.ts:42 ERROR 错误:未捕获(承诺中):TypeError:无法读取未定义的属性“自动完成”
我不知道我是否错过了什么。无论如何,这是指令的代码:
import {Directive, ElementRef, EventEmitter, Output} from '@angular/core';
import {NgModel} from '@angular/forms';
declare var google:any;
@Directive({
selector: '[Googleplace]',
providers: [NgModel],
host: {
'(input)' : 'onInputChange()'
}
})
export class GoogleplaceDirective {
@Output() setAddress: EventEmitter<any> = new EventEmitter();
modelValue:any;
autocomplete:any;
private _el:HTMLElement;
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', ()=> {
var place = this.autocomplete.getPlace();
this.invokeEvent(place);
});
}
invokeEvent(place:Object) {
this.setAddress.emit(place);
}
onInputChange() {
console.log(this.model);
}
}
使用方法如下:
<input type="text" class="form-control" placeholder="Location" name="Location" [(ngModel)]="address" #LocationCtrl="ngModel"
Googleplace (setAddress)="getAddressOnChange($event,LocationCtrl)">
【问题讨论】:
-
你确定
google.maps.places被定义了吗? -
感谢您的回答,但我只是照原样复制代码
-
我必须安装依赖项??
-
您应该尝试
console.log(google.maps)并查看它是否在此行之前拥有places属性:this.autocomplete = new google.maps.places.Autocomplete(input, {}); -
它给了我这个:{"Animation":{"BOUNCE":1,"DROP":2,"Zo":3,"Uo":4},"ControlPosition":{" TOP_LEFT":1,"TOP_CENTER":2,"TOP":2,"TOP_RIGHT":3,"LEFT_CENTER":4,"LEFT_TOP":5,"LEFT":5,"LEFT_BOTTOM":6,"RIGHT_TOP" :7,"RIGHT":7........(物体太长了)
标签: javascript angular google-maps