Angular 4 remove required validator conditionally

2020-05-22 15:50发布

In Angular 4 app I have a form model like this:

this.form = this._fb.group({
    title: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]],
    description: ['', [Validators.required, Validators.minLength(3)]]
});

Now what I want is to remove dynamically only the required validator from the control validators array. Something like this:

saveDraft() {
    this.form.controls['title'].removeValidator('required'); //Just a fake implementation for demonstration
}

This question is not the duplicate of the mentioned question. My case is different I just want to remove the required validator unknowingly the other ones.

8条回答
Melony?
2楼-- · 2020-05-22 16:29

I don't like clearing and setting validators, as I have to repeat all static validators (patterns, min, max, etc.) just to have a dynamic "required" validator.

I use a conditional validator:

export function conditionalValidator(condFn: (control: AbstractControl) => boolean,
validators: ValidatorFn | ValidatorFn[]): ValidatorFn {
  return (control) => {
    if (!condFn(control)) {
      return null;
    }

    if (!Array.isArray(validators)) {
      return validators(control);
    }

    return validators.map(v => v(control)).reduce((errors, result) =>
      result === null ? errors :
        (Object.assign(errors || {}, result))
    );
  };
}

I can then mix a static validator with a dynamic "required" condition:

this.fb.group({name: ['', [Validators.minLength(4),
                 conditionalValidator(this.isClientProj, Validators.required)]]}

Where isClientProj() is the condition function (closure)

查看更多
等我变得足够好
3楼-- · 2020-05-22 16:29

To Add Validators:

this.form = this._fb.group({
    title: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]],
    description: ['', [Validators.required, Validators.minLength(3)]]
});

or

this.form.get('title').setValidators([Validators.required,Validators.minLength(3), Validators.maxLength(50)]);

To Remove the 'Required' validator only, you can reset the validators.

saveDraft() {
     this.form.get('title').setValidators([Validators.minLength(3), Validators.maxLength(50)]);
     this.form.get('title').updateValueAndValidity();
}

updateValueAndValidity determines how the control propagates changes and emits events when the value and validators are changed

查看更多
登录 后发表回答