【问题标题】:Using setControl in nested reactive form以嵌套反应形式使用 setControl
【发布时间】:2018-11-04 07:50:26
【问题描述】:

当我在另一个 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([])
  }),
});

在上面的情况下,如果我想处理“标题,我可以写:

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

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

我试过用:

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

但它不起作用。

【问题讨论】:

  • 有什么理由要使用 setControl?
  • 我正在使用 setcontrol 和 getcontrol 来添加/删除该数组的字段

标签: angular angular2-forms angular-reactive-forms angular2-formbuilder


【解决方案1】:

FormGroupsetControl方法不支持嵌套的表单控制结构,它只会在当前层检测和设置表单控制,见setControl@ 987654322@.

对于您的情况,this.formulario.setControl('person.personDocument', something); 只会将新的表单控件(person.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
});

所以你需要在确切的层添加表单控件,例如:

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

【讨论】:

  • 请改正您的错字。该示例应使用 this.formulario 而不是 this.form 与您的其余答案一致。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2019-06-04
  • 2018-02-11
  • 2017-07-21
  • 2018-04-16
  • 2017-07-03
  • 2018-01-21
  • 1970-01-01
  • 2021-04-02
相关资源
最近更新 更多