-
-
Save Setubal18/db4e99e2c93e85e87abb0bd6bb2bc750 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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