@edersondev/ngx-form-error-message
Version:
Este pacote serve para controlar as mensagens de erro do formulário reativo do angular
111 lines (104 loc) • 5.67 kB
JavaScript
import { Subject } from 'rxjs';
import { FormControl } from '@angular/forms';
import * as i0 from '@angular/core';
import { InjectionToken, Directive, Inject, Input, NgModule } from '@angular/core';
import { takeUntil } from 'rxjs/operators';
const defaultErrors = {
min: (objMin) => `O valor mínimo é ${objMin.min} e o valor informado é ${objMin.actual}`,
max: (objMax) => `O valor máximo é ${objMax.max} e o valor informado é ${objMax.actual}`,
required: () => `Campo obrigatório`,
maxCheckbox: (value) => `Selecione no máximo ${value} opções.`,
email: () => `Informe um e-mail válido`,
matDatepickerParse: (matDatepickerParse) => (matDatepickerParse.text == 0 ? 'Informe uma data válida' : `O valor ${matDatepickerParse.text} é inválido`),
maxlength: (obj) => `A quantidade máxima de caracteres é ${obj.requiredLength} mas o campo possui ${obj.actualLength}`,
minlength: (obj) => `A quantidade mínima de caracteres é ${obj.requiredLength} mas o campo possui ${obj.actualLength}`,
pattern: (objPattern) => `O valor '${objPattern.actualValue}' não é compatível com o formato ${objPattern.requiredPattern}`,
mustMatch: () => `Os valores não conferem`,
fileSize: (objFilesize) => `O tamanho máximo permitido por arquivo é de ${objFilesize.limitSize}, o arquivo atual possui ${objFilesize.sizeFile}`,
requiredFileType: (obj) => `Tipo de arquivo inválido, este campo aceita arquivos do tipo: ${obj.types}`,
notMatch: () => `Os valores não devem ser iguais`,
selectedCheckbox: (selectItens) => `Selecione ${selectItens} opções`
};
const FORM_MSG_ERRORS = new InjectionToken('FORM_MSG_ERRORS', {
providedIn: 'root',
factory: () => defaultErrors
});
class NgxErrorMessageDirective {
constructor(errors, _elementRef) {
this.errors = errors;
this._elementRef = _elementRef;
this.customMessage = {};
this.destroy$ = new Subject();
this._elementRef.nativeElement.textContent = '';
}
ngOnInit() {
if (this.formControl instanceof FormControl) {
this._elementRef.nativeElement.textContent = this.setTextError();
this.formControl.valueChanges
.pipe(takeUntil(this.destroy$))
.subscribe(response => {
this._elementRef.nativeElement.textContent = this.setTextError();
});
}
else {
throw Error(`You need to pass a FormControl.Example:\n
<div [errorMessage]="form.get('input')"></div>\n`);
}
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
setTextError() {
const objErrors = (this.formControl != undefined ? this.formControl.errors : null);
if (objErrors != null) {
const key = Object.keys(objErrors).length - 1;
const firstElement = Object.keys(objErrors)[key];
const getError = this.errors[firstElement];
if (this.customMessage != undefined && this.customMessage[firstElement]) {
return this.customMessage[firstElement];
}
return getError(objErrors[firstElement]);
}
return '';
}
}
NgxErrorMessageDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.6", ngImport: i0, type: NgxErrorMessageDirective, deps: [{ token: FORM_MSG_ERRORS }, { token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Directive });
NgxErrorMessageDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "12.2.6", type: NgxErrorMessageDirective, selector: "[errorMessage]", inputs: { formControl: ["errorMessage", "formControl"], customMessage: "customMessage" }, ngImport: i0 });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.6", ngImport: i0, type: NgxErrorMessageDirective, decorators: [{
type: Directive,
args: [{
selector: '[errorMessage]'
}]
}], ctorParameters: function () { return [{ type: undefined, decorators: [{
type: Inject,
args: [FORM_MSG_ERRORS]
}] }, { type: i0.ElementRef }]; }, propDecorators: { formControl: [{
type: Input,
args: ['errorMessage']
}], customMessage: [{
type: Input
}] } });
class NgxFormErrorMessageModule {
}
NgxFormErrorMessageModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.6", ngImport: i0, type: NgxFormErrorMessageModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
NgxFormErrorMessageModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "12.2.6", ngImport: i0, type: NgxFormErrorMessageModule, declarations: [NgxErrorMessageDirective], exports: [NgxErrorMessageDirective] });
NgxFormErrorMessageModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "12.2.6", ngImport: i0, type: NgxFormErrorMessageModule, imports: [[]] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.6", ngImport: i0, type: NgxFormErrorMessageModule, decorators: [{
type: NgModule,
args: [{
declarations: [
NgxErrorMessageDirective
],
imports: [],
exports: [NgxErrorMessageDirective]
}]
}] });
/*
* Public API Surface of ngx-form-error-message
*/
/**
* Generated bundle index. Do not edit.
*/
export { NgxErrorMessageDirective, NgxFormErrorMessageModule };
//# sourceMappingURL=edersondev-ngx-form-error-message.js.map