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

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

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

问题

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

例如:

  1. profileForm = new FormGroup({
  2. names = new FormGroup({
  3. firstName: new FormControl(''),
  4. lastName: new FormControl('')
  5. })
  6. });

然后在一个输入字段中,我想直接访问路径 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:

  1. profileForm = new FormGroup({
  2. names = new FormGroup({
  3. firstName: new FormControl(''),
  4. lastName: new FormControl('')
  5. })
  6. });

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

答案1

得分: 1

以下是翻译好的部分:

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

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

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

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

然后在使用 getter 之前:

  1. <!-- 使用 getter -->
  2. <input [formControl]="firstNameControl" />
  1. <details>
  2. <summary>英文:</summary>
  3. In general you can use some in the way
  4. &lt;!--careful, it not work--&gt;
  5. &lt;input [formControl]=&quot;profileForm.get(&#39;names.firstName&#39;)&quot;/&gt;
  6. The problem is that [get][1] return an abstractControl so you need use a getter
  7. //in .ts
  8. get firstNameControl()
  9. {
  10. return profileForm.get(&#39;names.firstName&#39;) as FormControl
  11. }
  12. &lt;!--using the getter before--&gt;
  13. &lt;input [formControl]=&quot;firstNameControl&quot;/&gt;
  14. [1]: https://angular.io/api/forms/AbstractControl#get
  15. </details>
  16. # 答案2
  17. **得分**: 1
  18. 使用 `formControlName` 指令:
  19. ```html
  20. <form [formGroup]="profileForm">
  21. <div formGroupName="names">
  22. <input type="text" formControlName="firstName">
  23. <input type="text" formControlName="lastName">
  24. </div>
  25. </form>
英文:

Use formControlName directive:

  1. &lt;form [formGroup]=&quot;profileForm&quot;&gt;
  2. &lt;div formGroupName=&quot;names&quot;&gt;
  3. &lt;input type=&quot;text&quot; formControlName=&quot;firstName&quot;&gt;
  4. &lt;input type=&quot;text&quot; formControlName=&quot;lastName&quot;&gt;
  5. &lt;/div&gt;
  6. &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:

确定