以反应形式的formGroup.get与formGroup.controls-Angular [英] formGroup.get vs formGroup.controls in reactive form - Angular
问题描述
使用选择验证时是否有任何首选方式
Is there any preferred way when selecting validation using
-
myForm.controls['name'].valid
-
myForm.get('name').valid
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>
与
<div class="alert" *ngIf="!myForm.get('name').valid && myForm.get('name').touched">
{{ titleAlert }}
</div>
根据我在代码中签到的内容,get
具有以下代码:
From what I checked in the code, get
has this code:
AbstractControl.prototype.get = function (path) { return _find(this, path, '.'); };
我刚开始使用Angular,所以请您多多指教.
I have just started Angular, so an expert opinion would be appreciated.
推荐答案
FormGroup.get
就像您所发现的一样,被设计为通过path
访问目标formcontrol.而且它更常用于复杂的(多层嵌入)情况,这使得从多层嵌入形式获取目标控件变得容易,并且使代码清晰易懂.
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.
以下面的示例为例,您可以通过this.form.get('test.0')
而不是this.form.controls.test.controls[0]
来访问嵌入的FormArray的第一个元素:
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屋!