Skip to content

Instantly share code, notes, and snippets.

@AlexandreMT
Last active August 25, 2022 23:38
Show Gist options
  • Save AlexandreMT/150c1b0c8beca883770a63aa0e817949 to your computer and use it in GitHub Desktop.
Save AlexandreMT/150c1b0c8beca883770a63aa0e817949 to your computer and use it in GitHub Desktop.
import {Directive, ElementRef, Input, OnInit} from '@angular/core';
import { FormControl } from '@angular/forms';
type ErrorTypes = {
[key: string]: () => void;
};
@Directive({
selector: '[FormErrorsMessage]'
})
export class FormErrorsMessageDirective implements OnInit {
@Input() control: FormControl;
@Input() required = 'Campo obrigatório.';
@Input() email = 'Formato de e-mail inválido.';
@Input() pattern = 'Fora do padrão.';
@Input() minlength = 'Abaixo do tamanho mínimo.';
@Input() maxlength = 'Acima do tamanho máximo.';
@Input() max = 'Valor muito alto.';
@Input() min = 'Valor muito baixo.';
@Input() default = 'Campo preenchido incorretamente.';
@Input() customErrors = {};
constructor(
private _el: ElementRef,
) { }
ngOnInit(): void {
this._startErrorMessageExibition();
}
private _startErrorMessageExibition() {
this.control.valueChanges.subscribe(() => {
if (!this.control.errors) return this._clearErrorText();
const errorTypes = this._populateErrorTypes();
this._controlErrorsMessageExibition(errorTypes);
});
}
private _populateErrorTypes(): ErrorTypes {
const errorTypes = {
required: () => this._setErrorText(this.required),
email: () => this._setErrorText(this.email),
pattern: () => this._setErrorText(this.pattern),
minlength: () => this._setErrorText(this.minlength),
maxlength: () => this._setErrorText(this.maxlength),
max: () => this._setErrorText(this.max),
min: () => this._setErrorText(this.min),
};
this.control.errors && Object
.keys(this.customErrors)
.forEach(
(key) => errorTypes[key] = () => this._setErrorText(this.customErrors[key])
);
return errorTypes;
};
private _controlErrorsMessageExibition(errorTypes: ErrorTypes) {
this.control.errors && Object
.keys(this.control.errors)
.forEach(
(error) => errorTypes[error] ? errorTypes[error]() : this._setErrorText(this.default)
);
};
private _setErrorText(text: string) {
this._el.nativeElement.innerText = text;
}
private _clearErrorText() {
this._el.nativeElement.innerText = '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment