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

79 lines
1.9 KiB
TypeScript

import { Component, Inject, Input, OnInit } from '@angular/core';
import { UntypedFormGroup, ValidationErrors } from '@angular/forms';
import { DOCUMENT } from '@angular/common';
import { environment } from '../../../../../../../environments/environment';
@Component({
selector: 'app-errors-list',
templateUrl: './errors-list.component.html',
styleUrls: ['./errors-list.component.scss'],
})
export class ErrorsListComponent implements OnInit {
@Input() form: UntypedFormGroup;
public totalErrors = 0;
public firstErrorId = '';
public messages = [];
public hide_on_valid = true;
public environment = environment;
constructor(@Inject(DOCUMENT) private document: any) {}
ngOnInit() {
this.form.valueChanges.subscribe((data) => {
this.getFormValidationErrors();
});
this.getFormValidationErrors();
}
getFormValidationErrors(): void {
// console.log('%c ==>> Validation Errors: ', 'color: red; font-weight: bold; font-size:22px;');
let totalErrors = 0;
this.messages = [];
let firstErrorId = '';
Object.keys(this.form.controls).forEach((key) => {
const theKey = this.form.get(key);
const invalidData = theKey.invalid;
if (invalidData) {
if (!firstErrorId) {
firstErrorId = key;
}
}
const controlErrors: ValidationErrors = theKey.errors;
if (controlErrors != null) {
totalErrors++;
Object.keys(controlErrors).forEach((keyError) => {
if (!firstErrorId) {
firstErrorId = key;
}
const message = '' + key + ', ' + keyError + '';
this.messages.push(message);
});
}
});
this.totalErrors = totalErrors;
this.firstErrorId = firstErrorId;
if (totalErrors) {
}
}
scrollToFirstError(): void {
if (this.firstErrorId) {
const foundErrorField = this.document.querySelector('#' + this.firstErrorId);
if (foundErrorField) {
const offsetTop = foundErrorField.offsetTop;
scroll({
top: offsetTop,
behavior: 'smooth',
});
}
}
}
}