问题描述
限时送ChatGPT账号..在使用
选择验证时是否有任何首选方法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屋!
更多推荐
[db:关键词]
发布评论