Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2: get FormGroup by FormControl

can i get the FormGroup - the parent of the FormControl that i have? like this:

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

        console.log(formControl);
    }

}
like image 270
Meir Malka Avatar asked Oct 13 '16 10:10

Meir Malka


People also ask

How do I get the value of a FormGroup?

In order to get the complete form's values, we can use the FormGroup. getRawValue() method.

How do I use FormControl inside FormGroup?

How to add a FormControl to a FormGroup. To add, update, or remove controls in FormGroup , use the following commands: addControl() adds a control and updates its value and validity. removeControl() removes a control.

Can FormArray contains FormGroup?

The FormArray is a way to Manage collection of Form controls in Angular. The controls can be FormGroup, FormControl, or another FormArray. Because it is implemented as Array, it makes it easier dynamically add controls.


2 Answers

I currently have angular 5, but I'm sure on angular 4 it also worked like this:

formControl.parent

In my code, for example, I'm getting other control (by name) from the same group with:

formControl.parent.get(neighbourName)

like image 172
pbialy Avatar answered Sep 28 '22 08:09

pbialy


You can't access the parent of FormControl (see: https://github.com/angular/angular/issues/5635). But you can access the parent using Model-Driven Forms.

 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;


}
like image 20
jmachnik Avatar answered Sep 28 '22 06:09

jmachnik