以角度 2 设置来自组件的表单输入值

Ilj*_*lja 4 javascript forms angular

我在表单中有以下输入:

<form [ngFormModel]="newListingForm" (ngSubmit)="submitListing(newListingForm.value)">

<input type="text" placeholder="00.000" #mapLatitudeInput="ngForm" [ngFormControl]="newListingForm.controls['mapLatitudeInput']">

</form>
Run Code Online (Sandbox Code Playgroud)

当我拖动地图时,我需要更新它的值,所以从看起来像这样的相关组件:

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

}
Run Code Online (Sandbox Code Playgroud)

我认为正确的方法是//ISSUE HERE评论在哪里,但这会引发未定义的错误。

Thi*_*ier 5

您应该为拖动回调使用箭头函数:

map.addListener('drag', (event) => {
  this.newListingForm.controls.mapLatitudeInput.value
                                  = map.getCenter().lat()
});
Run Code Online (Sandbox Code Playgroud)

在这种情况下,this关键工作将是组件本身的实例。

也许您可以利用ngModel指令来设置输入的值而不是控件。它允许使用双向绑定。

<input type="text" placeholder="00.000"
       #mapLatitudeInput="ngForm"
       [ngFormControl]="newListingForm.controls['mapLatitudeInput']"
       [(ngModel)]="mapCoordinates.latitude">
Run Code Online (Sandbox Code Playgroud)

mapCoordinates对象将是具有两个字段的组件的属性:longitudelatitude

@Component({
  templateUrl : 'app/components/new-listing/new-listing.html',
  directives: [FORM_DIRECTIVES]
})
export class NewListingComponent {
  constructor() {
    this.mapCoordinates = {
      longitude: 0, latitude: 0
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

希望对你有帮助,蒂埃里