import { Component, Input } from "@angular/core";
import { AbstractControl } from "@angular/forms";
import { UpperCaseFirstPipe } from "../../pipes/upper-case-first-pipe";
@Component({
selector: "app-error",
imports: [UpperCaseFirstPipe],
template: `
@if (this.control && this.control.touched) {
@for (error of getErrorMessages(); track error) {
{{ error | upperCaseFirst }}
}
}
`,
})
export class Error {
@Input() control!: AbstractControl | null;
@Input() fieldName = "This field";
getErrorMessages() {
const messages: string[] = [];
if (this.control && this.control.errors) {
const errors = this.control.errors;
if (errors["required"]) {
messages.push(`${this.fieldName} is required.`);
}
if (errors["email"]) {
messages.push(`Please enter a valid email address.`);
}
if (errors["minlength"]) {
messages.push(
`${this.fieldName} must be at least ${errors["minlength"].requiredLength} characters.`,
);
}
if (errors["pattern"]) {
messages.push(`${this.fieldName} is formatted incorrectly.`);
}
if (errors["serverError"]) {
messages.push(errors["serverError"]);
}
}
return messages;
}
}