angular 2:通过FormControl获取FormGroup

时间:2016-10-13 10:39:14

标签: angular form-control

我可以获得FormGroup - 我拥有的FormControl的父级吗? 像这样:

    onBlur(formControl: FormControl) {
    var formGroup = formControl.parent // a FormGroup has the FormControl
    if (formControl.dirty) {

        console.log(formControl);
    }

}

3 个答案:

答案 0 :(得分:5)

您无法访问FormControl的父级(请参阅:https://github.com/angular/angular/issues/5635)。但您可以使用模型驱动的表单访问父级。

 constructor(private fb: FormBuilder) {

 this.form = fb.group({
   name: [],
   address: fb.group({
     city: ['', Validators.required],
     street: ['', Validators.required],
     zipCode: '',
     year: 2016
   }),
   groupDates: fb.group({
     fromDate_g: [''],
     toDate_g: ['', Validators.required]
   }, {validator: Validators.required}),
   dates: fb.group({
     fromDate: '',
     toDate: ''
   })
  });

  let datesGroup =  this.form.controls['dates'] as FormGroup;


}

答案 1 :(得分:3)

我目前有角度5,但我敢肯定在角度4上它也是如此:

formControl.parent

例如,在我的代码中,我通过以下方式从同一组中获取其他控件(按名称):

formControl.parent.get(neighbourName)

答案 2 :(得分:1)

似乎可能,但违反惯例。

 getParentForm(formControl: FormControl): FormGroup {
    return formControl['_parent'];
}