简体   繁体   English

Angular2更新FormArray中的表单值

[英]Angular2 Update form value inside FormArray

I need update 'lat' and 'lon' values inside FormArray: 我需要在FormArray中更新'lat'和'lon'值:

initRows() {
        return this._fb.group({
            address: "",
            lat: 0,
            lon: 0,
        });
   }




 initForm() {
        this.searchForm = this._fb.group({
        addresses: this._fb.array([this.initRows()]),
    });

I need update them after callback: 我需要在回调后更新它们:

 this.someService.getData().subscribe(
                  (response) => {this.data = response.json()
                                 this.lon = this.data.x;
                                 this.lat = this.data.y;
                                // UPDATE MY 'lat' and 'lon'
                  },
                  (error) => console.log('ERROR: ' + error)
          ); 

form.value object: form.value对象:

{

  "addresses": [
    {
      "address": {
        "text": "Weberweg, 58566, Kierspe, Nordrhein-Westfalen, DEU"
     },
      "lat": 0,
      "lon": 0
    },
     {
      "address": {
        "text": "Weberweg, 58566, Kierspe, Nordrhein-Westfalen, DEU"
     },
      "lat": 0,
      "lon": 0
    }
  ]
} 

PS 'lat' and 'lon' not an inputs, just data PS“ lat”和“ lon”不是输入,只是数据

I'm not sure is it "right" way, but you can do this: 我不确定这是“正确”的方法,但是您可以这样做:

    /* getter for addresses.
    get addresses() {
       this.seachForm.controls.addresses as FormArray;
    }

    /* function for loading data */
    public loadData() {
        this.someService.getData().subscribe(
           (response) => {
                          this.data = response.json()
                          this.lon = this.data.x; // it is global lon like I understood
                          this.lat = this.data.y; // it is global lat like I understood
                          this.addresses.controls.forEach((address) => {
                                 address.get('lat').setValue(this.lat);
                                 address.get('lon').setValue(this.lon);
                          }),
           (error) => console.log('ERROR: ' + error)
      );
}

Hope I got you right and this answer is helpful for you. 希望我做对了,这个答案对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM