Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get controls from nested form group

I have a FormGroup, nested in another FormGroup, where I want to get a certain control with get().

I tried the following solution, which doesn't work:

formGroup.get('formGroupKey').get('formControlKey');

But this throws an error. The first get() works (and correctly returns a FormGroup), but the second get throws an exception (path.split is not a function)

Any idea how I can solve that?

@Update

I solved it now this way (which is not a pretty solution though):

formGroup.get(tab.id)['controls'][segment.id];
like image 461
dave0688 Avatar asked Nov 29 '17 21:11

dave0688


People also ask

How do you use formControlName and deal with nested FormGroup?

With a parent FormGroup, the name input needs the syntax formControlName=name in order to be associated with the correct FormControl in the class. This syntax tells Angular to look for the parent FormGroup, in this case heroForm, and then inside that group to look for a FormControl called name.

Can we use FormControl and formControlName together?

FormControlNamelinkSyncs a FormControl in an existing FormGroup to a form control element by name.

How do you find form controls?

To fetch the value of a form control, we have to use value property on the instance of FormControl in our class. In the same way we can fetch the value in HTML template. city = new FormControl('Noida'); console. log(this.


1 Answers

This should work: this.formGroup.get(varibaleKey).get(variableKey2)

Here is some code:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  name = 'Angular 5';

  form: FormGroup;

  key1: string = 'test1';
  key2: string = 'test2';

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.form = this.formBuilder.group({
      test1: this.formBuilder.group({
        test2: ['testValue']
      }),
      another: ['testValue']
    });
    console.log(this.form.get(this.key1).get(this.key2));
  }
}

Here is an example: https://stackblitz.com/edit/angular-ipman8

like image 84
Gregor Doroschenko Avatar answered Oct 11 '22 20:10

Gregor Doroschenko