Cześć,
na wstępie chciałbym zaznaczyć, że Angular i TypeScript to dla mnie kompletnie nowe technologie.
W swoim projekcie korzystam z ReactiveForms
. Żeby nie musieć pod każdym polem pisać tej samej logiki, stworzyłem sobie komponent ValidationMessage
:
import { Component, Input } from '@angular/core';
import { AbstractControl, FormControl, ValidationErrors } from '@angular/forms';
@Component({
selector: 'app-validation-message',
imports: [],
templateUrl: './validation-message.component.html',
styleUrl: './validation-message.component.scss'
})
export class ValidationMessageComponent {
readonly defaultErrors: Record<string, (error: ValidationErrors) => string> = {
required: () => "Należy uzupełnić to pole!",
minlength: (error) => `Należy podać przynajmniej ${error['requiredLength']} znaków.`,
maxlength: (error) => `Przekroczono dozwolony limit znaków (${error['requiredLength']})!`,
email: () => "Należy podać prawidłowy adres E-Mail!"
};
@Input() showFor: AbstractControl = new FormControl();
get errorMessage(): string {
if (this.showFor.invalid && (this.showFor.dirty || this.showFor.touched)) {
const firstKey = Object.keys(this.showFor.errors!)[0];
const errorFn = this.defaultErrors[firstKey];
if (errorFn)
return errorFn(this.showFor.errors![firstKey]);
}
return "";
}
}
<div class="validation-error">
{{ errorMessage }}
</div>
Przykładowe wykorzystanie:
<input type="password" formControlName="password" id="password" class="form-input" placeholder="Hasło">
<app-validation-message [showFor]="frmLogin.controls['password']"></app-validation-message>
Czy użycie gettera w tym komponencie nie będzie sprawiać problemów z wydajnością?
Początkowo starałem się użyć signali, ale w żaden sposób nie mogłem zmusić jej do automatycznego aktualizowania treści błędu.
Z góry bardzo dziękuję!