以嵌套反应形式使用setControl

Mur*_*ida 0 angular2-forms angular2-formbuilder angular angular-reactive-forms

我想知道当我在另一个formBuilder组中有一个数组时,如何使用反应形式使用“ setControl”和“ get”。例如:

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([])
  }),
});
Run Code Online (Sandbox Code Playgroud)

在上述情况下,如果我想使用“标题”,则可以编写:

this.formulario.setControl('title', something);
this.formulario.get('title');
Run Code Online (Sandbox Code Playgroud)

但是当我要使用一个人内部的“ personDocument”来处理时,我不知道如何在上面写两个句子

我尝试使用:

this.formulario.setControl('person.personDocument', something);
this.formulario.get('person.personDocument')
Run Code Online (Sandbox Code Playgroud)

但这是行不通的。

Pen*_*gyy 5

FormGroup的setControl方法不支持嵌套的表单控件结构,它只会在当前层检测并设置表单控件,请参见setControl和registerControl。

对于您的情况,this.formulario.setControl('person.personDocument', something);只需将新的表单控件(的keyperson.personDocument)添加到当前层(您可以在formGroup的控件中进行确认)。

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
});
Run Code Online (Sandbox Code Playgroud)

因此,您将需要在确切的图层上添加表单控件,例如:

(this.formulario.get('person') as FormGroup).setControl('personDocument', new FormControl('aaa'));
Run Code Online (Sandbox Code Playgroud)