如何在角4反应形式中找到无效控件

sa_*_*sa_ 59 reactive angular angular-reactive-forms

我在Angular中有一个反应形式,如下所示:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

this.AddCustomerForm.valid返回false,但一切看起来都不错.

我试图通过检查控件集合中的status属性来查找.但我想知道是否有办法找到无效的并显示给用户?

Max*_*kyi 99

您可以简单地遍历每个控件并检查状态:

public findInvalidControls() {
    const invalid = [];
    const controls = this.AddCustomerForm.controls;
    for (const name in controls) {
        if (controls[name].invalid) {
            invalid.push(name);
        }
    }
    return invalid;
}
Run Code Online (Sandbox Code Playgroud)

  • @ AngularInDepth.com - 如果其中一个控件是表单组,则您的函数将返回无效表单组而不是无效的特定表单控件 (3认同)
  • 谢谢你,但我试过这个,即使这样也没有返回任何我的表格仍然无效,这很奇怪。我的意思是这段代码看起来不错,但为什么 form.valid 返回 false 没有任何意义 (2认同)

Mwi*_*iza 33

无效的 Angular 控件具有名为'ng-invalid'的 CSS 类。

在 Chrome 中的 DevTools 下,选择 Console 选项卡。

在控制台提示输入命令:

document.getElementsByClassName('ng-invalid')
Run Code Online (Sandbox Code Playgroud)

输出应与此类似: 在此处输入图片说明

在这种情况下,带下划线的文本用于表单控件listen-address。而圈起来的文字:.ng-invalid表示控件无效。

注意:在 chrome 中测试


Jet*_*tte 18

我刚刚解决了这个问题:每个表单字段都有效,但是表单本身仍然无效。

原来我在动态添加/删除控件的FormArray上设置了“ Validator.required”。因此,即使FormArray为空,它仍然是必需的,因此即使正确地填充了每个可见控件,该窗体也始终无效。

我没有找到表单的无效部分,因为我的'findInvalidControls'函数仅检查FormControl,而不检查FormGroup / FormArray。所以我更新了一下:

/* 
   Returns an array of invalid control/group names, or a zero-length array if 
   no invalid controls/groups where found 
*/
public findInvalidControlsRecursive(formToInvestigate:FormGroup|FormArray):string[] {
    var invalidControls:string[] = [];
    let recursiveFunc = (form:FormGroup|FormArray) => {
      Object.keys(form.controls).forEach(field => { 
        const control = form.get(field);
        if (control.invalid) invalidControls.push(field);
        if (control instanceof FormGroup) {
          recursiveFunc(control);
        } else if (control instanceof FormArray) {
          recursiveFunc(control);
        }        
      });
    }
    recursiveFunc(formToInvestigate);
    return invalidControls;
  }
Run Code Online (Sandbox Code Playgroud)

  • 哦哇。非常感谢,节省了我很多调查时间! (2认同)

tej*_*s n 17

.error每个反应形式的控件都存在一个属性。如果将此.error设置为 true,则表明控件无效。因此,循环遍历控件并检查该.error字段将使我们知道哪些字段/控件无效。

下面的代码将记录所有无效的控件

for (let el in this.ReactiveForm.controls) {
      if (this.ReactiveForm.controls[el].errors) {
        console.log(el)
      }
 }          
Run Code Online (Sandbox Code Playgroud)

或者可以将字段名称附加到数组或字符串中,并向用户指示哪些字段无效


小智 10

现在,在 angular 9 中,您可以使用 markAllAsTouched() 方法来显示无效的控件验证器:

this.AddCustomerForm.markAllAsTouched();
Run Code Online (Sandbox Code Playgroud)


Loo*_*lar 5

表单和所有控件都扩展了角度类 AbstractControl。每个实现都有一个验证错误的访问器。

let errors = this.AddCustomerForm.errors
// errors is an instance of ValidatorErrors
Run Code Online (Sandbox Code Playgroud)

api 文档包含所有引用 https://angular.io/api/forms/AbstractControl

编辑

我认为错误访问器是这样工作的,但是这个 github 链接显示还有其他一些人的想法与我相同 https://github.com/angular/angular/issues/11530

无论如何,通过使用控件访问器,您可以迭代表单中的所有 formControl。

Object.keys(this.AddCustomerForm.controls)
    .forEach( control => {
        //check each control here
        // if the child is a formGroup or a formArray
        // you may cast it and check it's subcontrols too
     })
Run Code Online (Sandbox Code Playgroud)