funky-framadate-front/src/app/features/shared/components/ui/form/errors-list/errors-list.component.ts

84 lines
2.1 KiB
TypeScript
Raw Normal View History

import { Component, Inject, Input, OnInit } from '@angular/core';
2021-05-04 09:33:28 +02:00
import { FormGroup, ValidationErrors } from '@angular/forms';
import { DOCUMENT } from '@angular/common';
2021-05-04 09:33:28 +02:00
@Component({
selector: 'app-errors-list',
templateUrl: './errors-list.component.html',
styleUrls: ['./errors-list.component.scss'],
})
export class ErrorsListComponent implements OnInit {
@Input() form: FormGroup;
public totalErrors = 0;
public firstErrorId = '';
2021-05-04 09:33:28 +02:00
public messages = [];
constructor(@Inject(DOCUMENT) private document: any) {}
2021-05-04 09:33:28 +02:00
ngOnInit() {
this.form.valueChanges.subscribe((data) => {
this.getFormValidationErrors();
});
this.getFormValidationErrors();
2021-05-04 09:33:28 +02:00
}
getFormValidationErrors(): void {
2021-05-18 10:47:16 +02:00
console.log('%c ==>> Validation Errors: ', 'color: red; font-weight: bold; font-size:22px;');
2021-05-04 09:33:28 +02:00
let totalErrors = 0;
this.messages = [];
let firstErrorId = '';
2021-05-04 09:33:28 +02:00
Object.keys(this.form.controls).forEach((key) => {
2021-05-04 09:42:56 +02:00
const theKey = this.form.get(key);
const invalidData = theKey.invalid;
2021-05-04 09:42:56 +02:00
if (invalidData) {
if (!firstErrorId) {
firstErrorId = key;
}
// totalErrors++;
// this.messages.push('' + key + ' est invalide');
2021-05-04 09:42:56 +02:00
}
const controlErrors: ValidationErrors = theKey.errors;
2021-05-04 09:33:28 +02:00
if (controlErrors != null) {
console.log('controlErrors', controlErrors);
totalErrors++;
Object.keys(controlErrors).forEach((keyError) => {
if (!firstErrorId) {
firstErrorId = key;
}
2021-05-04 09:33:28 +02:00
const message = '' + key + ', ' + keyError + '';
console.log(
'Key control: ' + key + ', keyError: ' + keyError + ', err value: ' + controlErrors[keyError]
);
2021-05-04 09:33:28 +02:00
this.messages.push(message);
});
}
});
this.totalErrors = totalErrors;
this.firstErrorId = firstErrorId;
2021-05-04 09:33:28 +02:00
2021-05-04 09:35:23 +02:00
if (totalErrors) {
console.log('Number of errors: ', totalErrors);
}
2021-05-04 09:33:28 +02:00
}
scrollToFirstError() {
if (this.firstErrorId) {
const foundErrorField = this.document.querySelector('#' + this.firstErrorId);
if (foundErrorField) {
const offsetTop = foundErrorField.offsetTop;
scroll({
top: offsetTop,
behavior: 'smooth',
});
}
console.log('foundErrorField', foundErrorField);
}
}
2021-05-04 09:33:28 +02:00
}