Last active
October 24, 2019 02:29
-
-
Save guiseek/eee2e6da0fb47740dee2be11237b9283 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
@Directive({ | |
selector: '[uiErrorBuilder], formControlName, ngModel, [ngModel], [formControlName], [formControl]', | |
exportAs: 'errorBuilder' | |
}) | |
export class ErrorBuilderDirective implements OnInit, OnDestroy { | |
@Input() messages: ErrorMessages = {}; | |
public message: string; | |
private sub: Subscription; | |
constructor( | |
@Inject(FORM_ERRORS) private errors, | |
private controlDir: NgControl | |
) { } | |
get control() { | |
return this.controlDir.control; | |
} | |
ngOnInit() { | |
this.sub = merge( | |
this.control.valueChanges | |
).subscribe((v) => { | |
const controlErrors = this.control.errors; | |
this.message = controlErrors ? this.getError(controlErrors) : ''; | |
}); | |
} | |
getError(errors) { | |
if (!errors) { | |
return; | |
} | |
const key = Object.keys(errors)[0]; | |
if (this.hasInMessages(key)) { | |
return this.messages[key]; | |
} | |
if (this.isDefaultMessage(key)) { | |
return this.errors[key](errors[key]); | |
} else { | |
return 'Erro desconhecido'; | |
} | |
} | |
isDefaultMessage(key) { | |
return Object.keys(this.errors).includes(key); | |
} | |
hasInMessages(key) { | |
if (!!!this.messages) { | |
return false; | |
} | |
return !!this.messages[key]; | |
} | |
ngOnDestroy() { | |
return this.sub && this.sub.unsubscribe(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment