All files / app/forms base.form.ts

93.25% Statements 83/89
94.11% Branches 16/17
100% Functions 8/8
93.25% Lines 83/89

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 901x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 156x 156x 1x 1x 9x 9x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 1x 1x 9x 9x 9x 2x 9x 9x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1014x 1014x 1014x 1014x 1014x 1014x 1014x     2x 1x 1x 3x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x  
import { FormBuilder, FormGroup } from '@angular/forms';
 
export abstract class BaseForm {
	formSubmit = false;
	formData: FormGroup;
	remoteProcess = false;
	remoteIsNotAvail = false;
	remoteErrorsKeys: any = [];
 
	abstract getFieldsConfig(): FormGroup;
 
	abstract getValidationMessages(): any;
 
	public constructor(public formBuilder: FormBuilder) {
		this.formData = this.getFieldsConfig();
	}
 
	protected clientValidate() {
		return this.formData.valid;
	}
 
	protected getMergedData(data: object) {
		return data;
	}
 
	validate(): boolean {
		this.clearErrors();
		this.formSubmit = true;
		return this.clientValidate();
	}
 
	clearErrors() {
		const remoteErrors = this.remoteErrorsKeys;
		const keys = Object.keys(remoteErrors);
		keys.forEach((fieldName) => {
			this.formData.controls[fieldName].setErrors(null);
		});
	}
 
	setErrors(errors: any) {
		const keys = Object.keys(errors);
 
		keys.forEach((fieldName) => {
			const errorsField = errors[fieldName];
			const errorsKey = Object.keys(errorsField);
 
			errorsKey.forEach((errorName) => {
				const error: any = {};
				error[errorName] = true;
				this.remoteErrorsKeys[fieldName] = errorName;
				this.formData.controls[fieldName].setErrors(error);
			});
		});
	}
 
	getErrors(fieldName: any) {
		const errorMessages = this.getValidationMessages();
		const keys = Object.keys(errorMessages);
		const errorsList: any = [];
 
		if (this.formSubmit === false) {
			return errorsList;
		}

		keys.forEach((currentFieldName) => {
			if (currentFieldName === fieldName) {
				const messagesKeys = Object.keys(errorMessages[currentFieldName]);
				messagesKeys.forEach((messageKey) => {
					if (this.formData.controls[currentFieldName].getError(messageKey) === true) {
						errorsList.push(errorMessages[currentFieldName][messageKey]);
					}
				});
			}
		});

		return errorsList;
	}
 
	collectData() {
		const data: any = {};
		const controls = this.formData.controls;
		const keys = Object.keys(controls);
 
		keys.forEach((fieldName: any) => {
			data[fieldName] = controls[fieldName].value;
		});
		return this.getMergedData(data);
	}
}