简体   繁体   English

如何在 Angular Reactive Forms 中执行 required-if?

[英]How to do required-if in Angular Reactive Forms?

I have a reactive form and based on the property fooRequired I want to set the field to be required or not.我有一个反应式表单,并且基于属性fooRequired我想将该字段设置为是否需要。

I can't change that because it set at initial.我无法更改它,因为它设置为初始值。 so what can I do?那我该怎么办?

fooRequired = false;

form = new FormGroup({
 foo: new FormControl(null, [Validators.required])
});

toggle() { this.fooRequired = !this.fooRequired; }

The following will do the trick:以下将解决问题:

toggle() {
  this.fooRequired = !this.fooRequired;
  this.form.controls.foo.setValidators(this.fooRequired ? null : [Validators.required]);
  this.form.controls.foo.updateValueAndValidity();
}

Here, based on the fooRequired boolean, the validators are set or removed.在这里,根据fooRequired布尔值,设置或删除验证器。 Finally, the new form control settings are updated.最后,更新新的表单控件设置。

You can use a custom function that gonna be responsible for adding or removing the Validators您可以使用一个自定义函数来负责添加或删除Validators

export function conditionalValidator(
  predicate: BooleanFn,
  validator: ValidatorFn,
  errorNamespace?: string
): ValidatorFn {
  return formControl => {
    if (!formControl.parent) {
      return null;
    }
    let error = null;
    if (predicate()) {
      error = validator(formControl);
    }
    if (errorNamespace && error) {
      const customError = {};
      customError[errorNamespace] = error;
      error = customError;
    }
    return error;
  };
}

Then you can use it inside you form control:然后你可以在你的表单控件中使用它:

this.myForm = this.fb.group({
  myEmailField: [
    "",
    [
      // some normal validatiors
      Validators.maxLength(250),
      Validators.minLength(5),
      Validators.pattern(/.+@.+\..+/),
      // custom validation
      conditionalValidator(
        // depends on fooRequired value
        () => this.fooRequired,
        Validators.required,
        "illuminatiError"
      )
    ]
  ]
});

Finally you can toggle the value of fooRequired and see the result:最后,您可以切换fooRequired的值并查看结果:

  toggle() {
    this.fooRequired = !this.fooRequired;
    this.myForm.get("myEmailField").updateValueAndValidity();
  }

Here is a live demo to help you with implementing the above answer这是一个现场演示,可帮助您实现上述答案

You need to use setValidator() and updateValueAndValidity() for your foo form control based on the fooRequired variable.您需要根据 fooRequired 变量对 foo 表单控件使用updateValueAndValidity() setValidator()updateValueAndValidity() These two functions will update the validation dynamically.这两个函数将动态更新验证。

Demo: https://stackblitz.com/edit/angular-setvalidators-jec7jo?file=src%2Fapp%2Fapp.component.ts演示: https : //stackblitz.com/edit/angular-setvalidators-jec7jo?file=src%2Fapp%2Fapp.component.ts

More to read: https://www.tektutorialshub.com/angular/how-to-add-validators-dynamically-using-setvalidators-in-angular/更多阅读: https : //www.tektutorialshub.com/angular/how-to-add-validators-dynamically-using-setvalidators-in-angular/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM