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条回答
Anthone
2楼-- · 2020-05-22 16:11
saveDraft() {
   this.form.get('title').setValidators([Validators.required, Validators.minLength(3)]);
   this.form.get('title').updateValueAndValidity();
}

saveDraft() {
 this.form.get('title').clearValidators();
 this.form.get('title').updateValueAndValidity();
}
查看更多
我命由我不由天
3楼-- · 2020-05-22 16:20

I had the same problem with saving entry as draft and prepared the following solution:

@Component({
    // ...
})
export class FormComponent{
    form: FormGroup;

    constructor(private fb: FormBuilder){
        this.form = this.fb.group({
            name: ['', Validators.required, Validators.maxLength(20)],
            description: ['', Validators.required, Validators.maxLength(200)],
            address: this.fb.group({
                line1: ['', Validators.required, Validators.maxLength(100)],
                line2: ['', Validators.maxLength(100)]
            })
        });
    }    

    validateDraft(formElement: FormGroup | FormArray | FormControl): boolean {
        let result = true;

        Object.keys(formElement.controls).forEach(field => {
            const control = formElement.get(field);

            if(control instanceof FormControl) {
                control.markAsTouched({ onlySelf: true });

                if(control.errors && control.errors['required']) {
                    control.markAsUntouched({ onlySelf: true });
                }
                else if(control.invalid) {
                    result = false;
                }
            } else if (control instanceof FormArray) {
                if (!this.validateDraft(control)) {
                    result = false;
                } 
            }else if (control instanceof FormGroup) {
                if (!this.validateDraft(control)) {
                    result = false;
                }   
            }
        });
    }

    saveDraft(){
        if(this.validateDraft(this.form)){
            //save draft - ignore required errors
        }
    }

    save(){
        if(this.form.valid){
            //save
        }
    }
}
查看更多
Summer. ? 凉城
4楼-- · 2020-05-22 16:21

if you want to add validation try this one.

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

if you want to remove validators try this one.

saveDraft() {
 this.form.get('title').clearValidators();
 this.form.get('title').updateValueAndValidity();
}
查看更多
SAY GOODBYE
5楼-- · 2020-05-22 16:22

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.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-05-22 16:27

Use empty array to remove all existing validators.

this.frmFeasibility.controls['pop_name'].setValidators([]);
this.frmFeasibility.controls['pop_name'].updateValueAndValidity();
查看更多
家丑人穷心不美
7楼-- · 2020-05-22 16:28

we can use setValidators to remove validation.

this.form.get('title').setValidators(null); 
this.form.get('title').setErrors(null); 
查看更多
登录 后发表回答