如何在 Angular(v2 及更高版本)反应形式中找到无效控件 [英] How to find the invalid controls in Angular(v2 onwards) reactive form
本文介绍了如何在 Angular(v2 及更高版本)反应形式中找到无效控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Angular 中有一个反应形式,如下所示:
I have a reactive form in Angular like below:
this.AddCustomerForm = this.formBuilder.group({
Firstname: ['', Validators.required],
Lastname: ['', Validators.required],
Email: ['', Validators.required, Validators.pattern(this.EMAIL_REGEX)],
Picture: [''],
Username: ['', Validators.required],
Password: ['', Validators.required],
Address: ['', Validators.required],
Postcode: ['', Validators.required],
City: ['', Validators.required],
Country: ['', Validators.required]
});
createCustomer(currentCustomer: Customer)
{
if (!this.AddCustomerForm.valid)
{
//some app logic
}
}
this.AddCustomerForm.valid 返回 false,但一切看起来都不错.
this.AddCustomerForm.valid returns false, but everything looks good.
我试图通过检查控件集合中的状态属性来查找.但是我想知道有没有办法找到无效的并显示给用户?
I have tried to find with checking the status property in the controls collection. But I wonder if there is a way to find the invalid ones and display to the user?
推荐答案
您可以简单地遍历每个控件并检查状态:
You can simply iterate over every control and check the status:
public findInvalidControls() {
const invalid = [];
const controls = this.AddCustomerForm.controls;
for (const name in controls) {
if (controls[name].invalid) {
invalid.push(name);
}
}
return invalid;
}
这篇关于如何在 Angular(v2 及更高版本)反应形式中找到无效控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文