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

79 lines
1.9 KiB
TypeScript
Raw Normal View History

import { Component, Inject, Input, OnInit } from '@angular/core';
import { UntypedFormGroup, ValidationErrors } from '@angular/forms';
import { DOCUMENT } from '@angular/common';
2021-11-12 18:17:49 +01:00
import { environment } from '../../../../../../../environments/environment';
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: UntypedFormGroup;
2021-05-04 09:33:28 +02:00
public totalErrors = 0;
public firstErrorId = '';
2021-05-04 09:33:28 +02:00
public messages = [];
2021-11-12 18:17:49 +01:00
public hide_on_valid = true;
public environment = environment;
2021-05-04 09:33:28 +02:00
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 11:46:35 +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;
}
2021-05-04 09:42:56 +02:00
}
const controlErrors: ValidationErrors = theKey.errors;
2021-05-04 09:33:28 +02:00
if (controlErrors != null) {
totalErrors++;
Object.keys(controlErrors).forEach((keyError) => {
if (!firstErrorId) {
firstErrorId = key;
}
2021-05-04 09:33:28 +02:00
const message = '' + key + ', ' + 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) {
}
2021-05-04 09:33:28 +02:00
}
2021-05-18 11:46:35 +02:00
scrollToFirstError(): void {
if (this.firstErrorId) {
const foundErrorField = this.document.querySelector('#' + this.firstErrorId);
if (foundErrorField) {
const offsetTop = foundErrorField.offsetTop;
scroll({
top: offsetTop,
behavior: 'smooth',
});
}
}
}
2021-05-04 09:33:28 +02:00
}