如何在angular2中的嵌套表单字段中获取和设置值?

时间:2017-07-18 12:05:56

标签: angular

我正在开发angular2应用程序并使用角度反应形式。 如何获得最内层元素的值并设置其值。

form : FormGroup;

constructor(private formBuilder: FormBuilder)
{
   this.form = formBuilder.group({
      'home_cleaning' : [{
           cities : FormBuilder.array([])
       }]
   });
}

setValue()
{
    let cities_array = [1,2,3,4];
    this.form.controls['home_cleaning']['cities'].setValue(cities_array);
}

getValue()
{
   console.log(this.form.controls['home_cleaning']['cities'].value);
}

在控制台中获取错误:无法读取属性' setValue / value'未定义的。

7 个答案:

答案 0 :(得分:4)

试试这个答案

form: FormGroup;

constructor(private formBuilder: FormBuilder) {
    this.form = formBuilder.group({
      'home_cleaning': formBuilder.group({
        cities: [] //if you want to set values as normal array if you want to create FormArray use new FormArray([]) and push formCotrols in this array.
      })
    });
}

setValue() {
    let cities_array = [1, 2, 3, 4];
    this.form.get(['home_cleaning','cities']).setValue(cities_array);
}

getValue() {
    console.log(this.form.get(['home_cleaning','cities']).value);
}

答案 1 :(得分:2)

如果您想用数据填充表单,则必须对其进行修补

this.form.patchValue(dataObject);

this.form.patchValue({
   'home_cleaning': { cities: 'value' }
});

使用patchValue,您可以通过为感兴趣的控件提供键/值对的对象,为FormGroup中的特定控件赋值。

您可以合并对象

this.form.patchValue(Object.assign(this.form.value, youNewDataObject)));

this.form.patchValue(dataObj, {selfOnly: true });

答案 2 :(得分:0)

  

试试这个:

   setValue() {
    let cities_array = [1, 2, 3, 4];
    this.form = this.formBuilder.group({
        home_cleaning: this.formBuilder.array([
            [({
                cities: cities_array,

            })],
        ]),
    });
}

答案 3 :(得分:0)

通过评论,您似乎只想将新值推送到表单数组,然后让我们只使用map,并推送新的表单控件:

setValue() {
  let cities_array = [1,2,3,4];
  let arr = this.form.get('home_cleaning.cities').controls;
  cities_array.map(city => arr.push(new FormControl(city)))
}

PS。在这里,我假设你有拼写错误,home_cleaning实际上是一个嵌套的表单组。

为了获得价值,只需:

this.form.get('home_cleaning.cities').value

答案 4 :(得分:0)

遇到了同样的问题,像这样解决了它:

this.newEmployeeForm = new FormGroup({

controls..............

and nested Form:
      PersonalAdress : new FormGroup({
            StreetName: new FormControl(null),
            StreetNumber: new FormControl(null),
            ZipCode : new FormControl(null),
            Region: new FormControl(null)

 })
})

所以我只使用在HTML代码中使用的路径:

 this.newEmployeeForm.get('PersonalAdress.City').setValue(data);

就像这样,只要您提供正确的路径,您甚至可以设置最深的嵌套表单元素。

请注意,我为get方法提供了一个字符串。

答案 5 :(得分:0)

    form : FormGroup;

    constructor(private formBuilder: FormBuilder)
    {
       this.form = this.formBuilder.group({
          'home_cleaning' : this.formBuilder.array([
             this.formBuilder.group({
                cities : this.formBuilder.array([])
             })
          ])
       });
    }

   setValue()
   {
      let cities_array = [1,2,3,4];
      (this.form.controls['home_cleaning'].value).forEach((value, key)=> {
         let citiesArray = <FormArray>(<FormArray>this.form.controls['home_cleaning']).controls[key].get('cities');
         for(let city of cities_array){
            citiesArray.push(new FormControl(city))
         }
      });
      this.getValue();
   }

   getValue()
   {
      (this.form.controls['home_cleaning'].value).forEach((value, key)=> {
         let citiesArray = <FormArray>(<FormArray>this.form.controls['home_cleaning']).controls[key].get('cities').value;
      });
   }

答案 6 :(得分:0)

我试图做一些类似的事情,发现这种模式在模板中运行良好:

<span class="label-error" *ngIf="(form.controls['parentControl'].controls['childControl'].invalid && attemptedSubmit)">Please select childControl.</span>