import { Component, Inject, Input, OnInit } from '@angular/core'; import { FormGroup, ValidationErrors } from '@angular/forms'; import { DOCUMENT } from '@angular/common'; @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 = ''; public messages = []; 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; } // totalErrors++; // this.messages.push('' + key + ' est invalide'); } const controlErrors: ValidationErrors = theKey.errors; if (controlErrors != null) { console.log('controlErrors', controlErrors); totalErrors++; Object.keys(controlErrors).forEach((keyError) => { if (!firstErrorId) { firstErrorId = key; } const message = '' + key + ', ' + keyError + ''; console.log( 'Key control: ' + key + ', keyError: ' + keyError + ', err value: ' + controlErrors[keyError] ); this.messages.push(message); }); } }); this.totalErrors = totalErrors; this.firstErrorId = firstErrorId; if (totalErrors) { console.log('Number of errors: ', totalErrors); } } 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); } } }