首页 > 解决方案 > Delete errors from one Form Field in Angular's Reactive Forms

问题描述

Using Angular 8 I have a Reactive form:

form: FormGroup;

submitting: boolean = false;

ngOnInit() {

  this.form = this.formBuilder.group({ 
    income: [''],
    period: ['']
  })

}

onSubmit() {

  if (this.form.valid) {

    this.submitting = true;

    let model: Model = { 
      income: this.form.value.income,
      period: this.form.value.period
    }

    // Remaining code

}

When form.value.income has no value I would like to delete any errors associated with form.value.period and be able to submit the form.

How can I do this?

标签: angularangular8angular-reactive-forms

解决方案


好吧,我想我会试一试。

最佳实践是创建一个自定义Validator(在您自己的单独文件中进行分离),然后将其应用于Validator全局formBuilder validator选项。

例子:

has-no-value.validator.ts

 import { FormGroup } from '@angular/forms';

export const hasNoValue = (controlName: string, matchingControlName: string) => { 
  return (formGroup: FormGroup) => {
      const control = formGroup.controls[controlName];
      const matchingControl = formGroup.controls[matchingControlName];

      if (control.value === '') {
          matchingControl.setErrors(null);
      }
   }
}

app.component.ts

ngOnInit() {

  this.form = this.formBuilder.group({ 
    income: ['', [Validators.required]],
    period: ['', [Validators.required]]
  }, {
    validator: hasNoValue('income', 'period')
  });
}

一个工作示例:https ://stackblitz.com/edit/angular-rd15bu


推荐阅读