Renê Silva Lima
Renê Silva Lima

Reputation: 2815

Access form property inside a nested formGroup

How to access a form property inside a nested formGroup? That might sound confuse but I think the code will help you guys understand. This is the formGroup, and as you can see there's an array inside the formGroup:

      this.formDadosBancarios = this._fb.group({
        id: [''],
        dados_titular: this._fb.array([
          this.initTitular()
        ])
      })

   initTitular(){
        return this._fb.group({
            titular: ['', [<any>Validators.required, <any>Validators.minLength(3)]],
            cnpj: [''],
            cpf: ['', Validators.required],
            data_nasc: ['', Validators.required],
            agencia: ['', <any>Validators.required ],
            banco: ['', <any>Validators.required],
            conta: ['', <any>Validators.required],
            tipo:  ['', <any>Validators.required],
            pessoa_juridica: ['']
        })
    }

and here's the snippet code where I try to access the property cpf that is inside ìnitTitular` (I know this code bellow looks nonsense but is just to ilustrate the logic):

const cpfCtrl: AbstractControl = this.formDadosBancarios.get('dados_titular').get('cpf');

Upvotes: 2

Views: 241

Answers (1)

n00dl3
n00dl3

Reputation: 21564

You just need to use the at(index: number) : AbstractControl method of FormArray

let array = <FormArray> this.formDadosBancarios.get('dados_titular');
let cpf = array.at(0).get("cpf");

I think you can also do this (but I'm unsure for FormArray's [0]). See the docs

this.formDadosBancarios.get('dados_titular[0].cpf'); //maybe it's ".0" instead of "[0]"
this.formDadosBancarios.get(['dados_titular',0,'cpf']);

Upvotes: 2

Related Questions