Angular 4 remove required validator conditionally

后端 未结 10 1939
[愿得一人]
[愿得一人] 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

    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
            }
        }
    }
    

提交回复
热议问题