【问题标题】:Setting form input value from component in angular 2以角度 2 从组件设置表单输入值
【发布时间】:2016-04-19 22:10:07
【问题描述】:

我在表单中有以下输入:

<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 注释所在的位置,但这会引发未定义的错误。

【问题讨论】:

标签: javascript forms angular


【解决方案1】:

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

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

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

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

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

mapCoordinates 对象将是您的组件的一个属性,其中包含两个字段:longitudelatitude

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

希望对你有帮助 蒂埃里

【讨论】:

  • 我现在收到以下错误:无法设置只有 getter 的 # 的属性值
  • 在我的文本编辑器中出现以下错误:属性 'mapLatitudeInput' 在类型 '{ [key: string]: AbstractControl; 上不存在}'
  • 我认为你应该利用ngModel 指令...我更新了我的答案;-)
  • 我之前尝试过使用 ngModel,但没有弄清楚。如何在组件内绑定 mapCoordinates?我试过把 mapCoordinates: Object;在我的类导出行下并像 this.mapCoordinates.latitude 一样访问它,但这似乎不起作用
  • 我更新了我的答案。实际上,您只需要初始化组件属性...然后使用[(ngModel)] 将您的输入链接到它上面,并使用两种方式绑定。
猜你喜欢
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
  • 2020-03-31
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
相关资源
最近更新 更多