【发布时间】:2019-07-06 05:20:28
【问题描述】:
我有一个单字段表单,数据没有发送到我的FormGroup。当我出于某种奇怪的原因记录它时它是空的。
我的 TS 文件
addressData: FormGroup;
submitted = false;
success = false;
userLat: number;
userLng: number;
private geoCoder: google.maps.Geocoder;
constructor(private maps: MapsAPILoader, private bulider: FormBuilder, private ref: ChangeDetectorRef) { }
ngOnInit() {
this.addressData = this.bulider.group({
address: ["", Validators.required],
});
console.log("Init data: " + this.addressData.controls['address'].value);
this.maps.load().then(() => {
this.geoCoder = new google.maps.Geocoder();
});
}
getAddress() {
this.submitted = true;
// I commented this out to see if the geocoder works
// if (this.addressData.invalid) {
// console.error("Invalid address! Address: " + this.addressData.value);
// return;
// }
this.geoCoder.geocode({ 'address': this.addressData.controls['address'].value }, (results, status) => {
if (status === google.maps.GeocoderStatus.OK) {
this.userLat = results[0].geometry.location.lat();
this.userLng = results[0].geometry.location.lng();
this.ref.detectChanges();
this.success = true;
} else {
// The address is empty, therefore gives me invalid_request
alert('Geocode was not successful for the following reason: ' + status + " and Address: " + this.addressData.controls['address'].value);
}
});
this.submitted = false;
}
}
HTML
<div>
<form [formGroup]="addressData" (ngSubmit)="getAddress()">
<input class="addressBar" type="text" placeholder="Address" maxlength="30" autofocus>
<br><br><button class="searchBtn" type="submit">Search</button>
</form>
</div>
我知道您可以在 HTML 中使用 #address,并将其传递给方法 getAddress(),但我想这样做,因为我将使用错误消息来提供用户反馈。
预期:
我希望根据需要验证地址并在地理编码器中使用。
实际:
FormGroup 为空且始终无效(无论您输入什么内容),因此无法在地理编码器中使用。
【问题讨论】:
标签: angular forms google-geocoder angular-google-maps