dave0688
dave0688

Reputation: 5770

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];

Upvotes: 7

Views: 5155

Answers (1)

Gregor Doroschenko
Gregor Doroschenko

Reputation: 11696

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

Upvotes: 5

Related Questions