【问题标题】:Angular2 Update form value inside FormArrayAngular2更新FormArray中的表单值
【发布时间】:2018-05-21 08:30:40
【问题描述】:

我需要更新 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()]),
    });

我需要在回调后更新它们:

 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 对象:

{

  "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
    }
  ]
} 

附: 'lat' 和 'lon' 不是输入,只是数据

【问题讨论】:

    标签: angular formarray


    【解决方案1】:

    我不确定它是否“正确”的方式,但你可以这样做:

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

    希望我说对了,这个答案对你有帮助。

    【讨论】:

    • 问题是我正在尝试在服务器响应后更新这些值,并且这种 FormGroup 可以是多个(动态添加/删除字段)。获取当前FormGroup控件的要点
    • 我可以不得到孔数组,只得到当前的formGroup吗?
    猜你喜欢
    • 1970-01-01
    • 2017-09-23
    • 2016-06-05
    • 2019-02-23
    • 1970-01-01
    • 2017-05-18
    • 2017-06-13
    • 1970-01-01
    • 2018-01-09
    相关资源
    最近更新 更多