In Angular 4 app I have a form model like this:
this.form = this._fb.group({
title: [\'\', [Validators.required, Validators.minLength(3), Validators.maxLengt
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
}
}
}