Angular 4 remove required validator conditionally

后端 未结 10 1898
[愿得一人]
[愿得一人] 2021-02-01 01:26

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

this.form = this._fb.group({
    title: [\'\', [Validators.required, Validators.minLength(3), Validators.maxLengt         


        
10条回答
  •  生来不讨喜
    2021-02-01 02:09

    Unfortunately Angular doesn't have a removeValidator capability at this point in time. All you can do is re-set the validators without the one you want to remove, so you need to know which validators you want to keep rather than which one you want to remove. so this:

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

    Is the closest you have to a remove function. You can't access the current validators on a formcontrol either to try and write your own remove function. The best you could do is write your own form control validation manager class that can keep track of the validators on a given control and manage them for you.

提交回复
热议问题