3

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.

2
  • Any reason why you want to use setControl? Commented May 25, 2018 at 1:36
  • I'm using setcontrol and getcontrol to add/remove field of this array Commented May 25, 2018 at 2:40

1 Answer 1

16

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'));
Sign up to request clarification or add additional context in comments.

1 Comment

Please, resolve your typo. The example should use this.formulario instead of this.form to be in consens with the rest of your answer. Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.