Reactive Form: 一个 FormGroupName / FormControlname 中的多个表单层级

huangapple go评论49阅读模式
英文:

Reactive Form: Multiple layers of a form in one FormGroupName / FormControlname

问题

在一个响应式表单中,是否可以在一个 formGroupNameformControlName 指令中传递多层表单?

例如:

profileForm = new FormGroup({
  names = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl('')
  })
});

然后在一个输入字段中,我想直接访问路径 name.firstName,而不需要在一个 div 中使用外部的 formGroupName

英文:

Is it possible to pass in a reactive form multiple layers of a form in one formGroupName / formControlName Directive?

For example:

profileForm = new FormGroup({
  names = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl('')
  })
});

And in an Input Field i want to directly access the path name.firstName without an outer formGoupName at a div.

答案1

得分: 1

以下是翻译好的部分:

一般来说,您可以使用以下方式:

<!-- 小心,这种方式不起作用 -->
<input [formControl]="profileForm.get('names.firstName')" />

问题在于 [get][1] 返回一个抽象控件,因此您需要使用一个 getter:

// 在 .ts 文件中
get firstNameControl() {
    return profileForm.get('names.firstName') as FormControl
}

然后在使用 getter 之前:

<!-- 使用 getter -->
<input [formControl]="firstNameControl" />

<details>
<summary>英文:</summary>

In general you can use some in the way

    &lt;!--careful, it not work--&gt;
    &lt;input [formControl]=&quot;profileForm.get(&#39;names.firstName&#39;)&quot;/&gt;

The problem is that [get][1] return an abstractControl so you need use a getter

    //in .ts
    get firstNameControl()
    {
        return profileForm.get(&#39;names.firstName&#39;) as FormControl
    }
    
        &lt;!--using the getter before--&gt;
        &lt;input [formControl]=&quot;firstNameControl&quot;/&gt;

  [1]: https://angular.io/api/forms/AbstractControl#get



</details>



# 答案2
**得分**: 1

使用 `formControlName` 指令:

```html
<form [formGroup]="profileForm">
  <div formGroupName="names">
    <input type="text" formControlName="firstName">
    <input type="text" formControlName="lastName">
  </div>
</form>
英文:

Use formControlName directive:

  &lt;form [formGroup]=&quot;profileForm&quot;&gt;
    &lt;div formGroupName=&quot;names&quot;&gt;
       &lt;input type=&quot;text&quot; formControlName=&quot;firstName&quot;&gt;
       &lt;input type=&quot;text&quot; formControlName=&quot;lastName&quot;&gt;
    &lt;/div&gt;
  &lt;/form&gt;

huangapple
  • 本文由 发表于 2023年6月26日 14:53:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76554185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定