Using setControl in nested reactive form

Murilo Góes de Almeida picture Murilo Góes de Almeida · May 25, 2018 · Viewed 10.3k times · Source

I would like to know what I have to do to use the "setControl" and "get" in a reactive form when I have an array inside of another formBuilder group. For instance:

this.formulario = this.formBuilder.group({
  title: [this.racPessoa.title, [Validators.required]],
  description: [this.racPessoa.description, [Validators.required]],
  person: this.formBuilder.group({
    idPerson:[this.racPessoa.person.idPerson],
    name:[this.racPessoa.person.nome],
    personDocument: this.formBuilder.array([])
  }),
});

In the case above, if I want to handle with the "title, I can write:

this.formulario.setControl('title', something);
this.formulario.get('title');

But I don't know how to write both sentences above when I want to handle with the "personDocument", which is inside of a person

I've tried to use:

this.formulario.setControl('person.personDocument', something);
this.formulario.get('person.personDocument')

But it doesn't work.

Answer

Pengyy picture Pengyy · May 25, 2018

FormGroup's setControl method doesn't support for nested form control structures, it will just detect and set form control at current layer, see setControl and registerControl.

For your case, this.formulario.setControl('person.personDocument', something); will just add new form control(key of person.personDocument) to the your current layer(you can confirm at your formGroup's controls).

this.formulario = this.formBuilder.group({
  title: [this.racPessoa.title, [Validators.required]],
  description: [this.racPessoa.description, [Validators.required]],
  person: this.formBuilder.group({
    idPerson:[this.racPessoa.person.idPerson],
    name:[this.racPessoa.person.nome],
    personDocument: this.formBuilder.array([])
  }),
  'person.personDocument': something     // newly added form control
});

So you will need to add form control at the exact layer, for example:

(this.formulario.get('person') as FormGroup).setControl('personDocument', new FormControl('aaa'));