反应形式的 formGroup.get 与 formGroup.controls

编程入门 行业动态 更新时间:2024-10-28 01:20:32
本文介绍了反应形式的 formGroup.get 与 formGroup.controls - Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在使用

选择验证时是否有任何首选方法myForm.controls['name'].validmyForm.get('name').valid

因为两者似乎只是在语法上不同,但实现了相同的目标.

{{ titleAlert }}

根据我在代码中检查的内容,get 具有以下代码:

AbstractControl.prototype.get = function (path) { return _find(this, path, '.');};

我刚刚开始使用 Angular,因此非常感谢专家的意见.

解决方案

正如你所发现的,FormGroup.get 旨在通过它的 path 访问目标表单控件.并且它更常用于复杂的(多层嵌入)情况,这样可以很容易地从多层嵌入表单中获取目标控件,也使代码清晰易懂.

以下面为例,你可以简单地通过this.form.get('test.0')而不是this.form.controls来访问嵌入FormArray的第一个元素.test.controls[0]:

this.form = this.formBuilder.group({测试:this.formBuilder.array([['表单数组中的表单控件 1'],['表单数组中的表单控件 1'],...])});

Is there any preferred way when selecting validation using

myForm.controls['name'].valid myForm.get('name').valid

as both seems to be only syntactically different but achieving the same goal.

<label>Name
  <input type="text" formControlName="name">
</label>
<div class="alert" *ngIf="!myForm.controls['name'].valid && myForm.controls['name'].touched">
  {{ titleAlert }}
</div>

Same as

<div class="alert" *ngIf="!myForm.get('name').valid && myForm.get('name').touched">
  {{ titleAlert }}
</div>

From what I checked in the code, get has this code:

AbstractControl.prototype.get = function (path) { return _find(this, path, '.'); };

I have just started Angular, so an expert opinion would be appreciated.

解决方案

Just like what you have found, FormGroup.get is designed to access target formcontrol by it's path. And it's more often used for complicated(multi layer embed) situation, which makes it easy to get the target control from multi layer embed form and also makes code clear and easily to understand.

Take below as a example, you can simply access the first element of the embed FormArray by this.form.get('test.0') instead of this.form.controls.test.controls[0]:

this.form = this.formBuilder.group(
  {
    test: this.formBuilder.array(
      [
        ['form control 1 in form array'],
        ['form control 1 in form array'],
        ...
      ]
    )
  }
);

这篇关于反应形式的 formGroup.get 与 formGroup.controls - Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 09:45:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1000403.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:形式   formGroup   controls

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!