反应形式的 formGroup.get 与 formGroup.controls - Angular [英] formGroup.get vs formGroup.controls in reactive form - Angular

查看:21
本文介绍了反应形式的 formGroup.get 与 formGroup.controls - Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用

选择验证时是否有任何首选方法
  • myForm.controls['name'].valid
  • myForm.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屋!

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