在嵌套反应形式中使用 setControl [英] Using setControl in nested reactive form

查看:32
本文介绍了在嵌套反应形式中使用 setControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当我在另一个 formBuilder 组中有一个数组时,我必须做什么才能以反应形式使用setControl"和get".例如:

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([])
  }),
});

在上面的例子中,如果我想处理title",我可以这样写:

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

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

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

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

我尝试使用:

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

但它不起作用.

推荐答案

FormGroupsetControl 方法不支持嵌套表单控件结构,它只会检测并在当前层设置表单控件,参见 setControlregisterControl.

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.

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

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'));

这篇关于在嵌套反应形式中使用 setControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆