我在表单中输入以下内容:
<form [ngFormModel]="newListingForm" (ngSubmit)="submitListing(newListingForm.value)">
<input type="text" placeholder="00.000" #mapLatitudeInput="ngForm" [ngFormControl]="newListingForm.controls['mapLatitudeInput']">
</form>
在拖动地图时,需要更新其值,因此从相关组件中看起来像这样:
import {Component} from 'angular2/core';
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, Validators} from 'angular2/common';
@Component({
templateUrl : 'app/components/new-listing/new-listing.html',
directives: [FORM_DIRECTIVES]
})
export class NewListingComponent {
//Costructor
constructor(
fb: FormBuilder
){
//New Listing Form
this.newListingForm = fb.group({
'mapLatitudeInput': ['', Validators.required]
});
}
//Google maps
loadMap(latitude, longitude) {
var map = new google.maps.Map(document.getElementById('listing-map'), {
center: {lat: latitude, lng: longitude},
zoom: 18,
scrollwheel: false,
mapTypeControl: false,
streetViewControl: false
});
//Update coordinates on map drag
map.addListener('drag', function(event) {
//ISSUE HERE
this.newListingForm.controls.mapLatitudeInput.value = map.getCenter().lat()
//console.log(map.getCenter().lat());
//console.log(map.getCenter().lng());
});
}
//Todo Form submission
submitListing(value: string): void {
console.log("Form Submited");
}
//Log error
logError(err) {
console.error('Error: ' + err);
}
}
我认为正确的方法是// ISSUE HERE注释所在的位置,但这会引发未定义的错误.
解决方法:
您应该将箭头函数用于拖动回调:
map.addListener('drag', (event) => {
this.newListingForm.controls.mapLatitudeInput.value
= map.getCenter().lat()
});
在这种情况下,此键将是组件本身的实例.
也许您可以利用ngModel指令来设置输入值而不是控件.它允许使用两种方式的绑定.
<input type="text" placeholder="00.000"
#mapLatitudeInput="ngForm"
[ngFormControl]="newListingForm.controls['mapLatitudeInput']"
[(ngModel)]="mapCoordinates.latitude">
mapCoordinates对象将是组件的一个属性,具有两个字段:经度和纬度.
@Component({
templateUrl : 'app/components/new-listing/new-listing.html',
directives: [FORM_DIRECTIVES]
})
export class NewListingComponent {
constructor() {
this.mapCoordinates = {
longitude: 0, latitude: 0
};
}
}
希望对您有帮助,
蒂埃里
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。