A comprehensive Angular forms utility library for streamlined validation, error handling, and accessible error display.
npm install @spider-baby/utils-forms[sbFormControlFirstError]
typescript
// Component
export class LoginFormComponent {
protected _form: FormGroup = this.fb.nonNullable.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(3)]],
rememberMe: [false, []]
});
}
`
`html
[sbFormControlFirstError]="_form"
(ngSubmit)="submit()">
formControlName="email"
placeholder="Enter your email"/>
formControlName="password"
placeholder="Enter your password"/>
@if(_form.controls.password.errors?.['firstError']; as err){
{{err}}
}
`
#### Advanced Configuration
`html
[sbFormControlFirstError]="myForm"
[customErrorMessages]="customMessages">
[sbFormControlFirstError]="myForm"
[showUntouched]="true">
`
#### Inputs
| Property | Type | Default | Description |
| ------------------------- | ----------------------- | ------------ | ----------------------------------- |
| sbFormControlFirstError | FormGroup | required | The reactive form to monitor |
| customErrorMessages | CustomErrorMessageMap | undefined | Custom error message mappings |
| showUntouched | boolean | false | Show errors before user interaction |
$3
A standalone component that displays validation errors with smooth animations and accessibility features.
Selector: sb-first-error
#### Features
- Displays only the first validation error
- Smooth fade-in animation for error appearance
- ARIA live regions for screen reader compatibility
#### Usage
`html
formControlName="email"
placeholder="Enter your email"/>
`
#### Styling
The component uses CSS custom properties for easy theming:
`css
sb-first-error {
--error-color: #custom-error-color;
}
`
Default styling:
- Color: Material Design error color with fallback (var(--mat-sys-error, #d9534f);)
- Font size: 0.875rem
- Smooth fade-in animation
- Accessible spacing and layout
#### Inputs
| Property | Type | Description |
| --------- | ----------------- | ---------------------------------------------------- |
| control | AbstractControl | Required. The form control to display errors for |
Installation & Setup
$3
`typescript
import {
FirstErrorDirective,
FirstErrorComponent
} from '@spider-baby/utils-forms';
@Component({
standalone: true,
imports: [
ReactiveFormsModule,
FirstErrorDirective,
FirstErrorComponent,
// ...other imports
],
// ...component definition
})
export class MyFormComponent { }
`
$3
`html
`
Real-World Example
Here's a complete login form implementation using the library:
`typescript
// login.component.ts
@Component({
selector: 'sb-login-form',
standalone: true,
imports: [
ReactiveFormsModule,
FirstErrorDirective,
FirstErrorComponent,
// ...other imports
],
templateUrl: './login.component.html',
styleUrl: './login.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LoginFormComponent {
private fb = inject(FormBuilder)
protected _form: FormGroup = this.fb.nonNullable.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(3)]],
rememberMe: [false, []]
});
submit() {
if (!this._form.valid) return;
const dto: LoginFormDto = {
email: this._form.controls.email.value,
password: this._form.controls.password.value,
rememberMe: this._form.controls.rememberMe.value,
};
this.login.emit(dto);
}
}
`
`html
[sbFormControlFirstError]="_form"
(ngSubmit)="submit()"
class="login-form">
type="email"
formControlName="email"
placeholder="Enter your email"/>
type="password"
formControlName="password"
placeholder="Enter your password"/>
`
Error Message Customization
$3
The library provides sensible defaults for common validation errors:
| Error Key | Example Message |
| ---------------- | ------------------------------------------------------------------------------------------------------------------- |
| required | Email is required. |
| email | Please enter a valid email address. |
| minlength | Password must be at least 8 characters. |
| maxlength | Field must be no more than 20 characters. |
| pattern | Field format is invalid. |
| min | Value must be at least 1. |
| max | Value must be no more than 100. |
| passwordMismatch | Passwords do not match. |
| mustMatch | Fields do not match. |
| whitespace | Field cannot contain only whitespace. |
| forbiddenValue | Field cannot be "forbidden". |
| asyncValidation | Field validation is pending... |
| invalidDate | Please enter a valid date. |
| futureDate | Date must be in the future. |
| pastDate | Date must be in the past. |
| strongPassword | Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character. |
| phoneNumber | Please enter a valid phone number. |
| url | Please enter a valid URL. |
| unique | This field is already taken. |
| fileSize | File size must be less than 2MB. |
| fileType | Only PDF, DOCX files are allowed. |
> Note: Some messages are parameterized and will display the actual field name or value as appropriate.
$3
`typescript
import { CustomErrorMessageMap } from '@spider-baby/utils-forms';
const customMessages: CustomErrorMessageMap = new Map([
['email', (field, error) => {
if (error.required) return 'Email address is mandatory';
if (error.email) return 'Please provide a valid email format';
return '';
}],
['password', (field, error) => {
if (error.required) return 'Password cannot be empty';
if (error.minlength) return 'Password must be at least 8 characters long';
return '';
}],
]);
`
`html
[sbFormControlFirstError]="myForm"
[customErrorMessages]="customMessages">
`
#### 🌎 Example: Custom Error Messages in Spanish
`typescript
import { CustomErrorMessageMap } from '@spider-baby/utils-forms';
const customMessagesEs: CustomErrorMessageMap = new Map([
['email', (field, error) => {
if (error.required) return 'El correo electrónico es obligatorio';
if (error.email) return 'Por favor, introduce un correo electrónico válido';
return '';
}],
['password', (field, error) => {
if (error.required) return 'La contraseña no puede estar vacía';
if (error.minlength) return 'La contraseña debe tener al menos 8 caracteres';
return '';
}],
]);
`
`html
[sbFormControlFirstError]="myForm"
[customErrorMessages]="customMessagesEs">
`
#### Custom Error Template
You can provide a custom error message template to sb-first-error using the customErrorTemplate input. This allows you to fully control the rendering and styling of error messages.
Usage:
`html
*{{errorMessage}}*
`
Inputs Table:
| Property | Type | Description |
|-----------------------|-----------------------------|--------------------------------------------------|
| control | AbstractControl | Required. The form control to display errors for |
| customErrorTemplate | TemplateRef | Optional. Custom template for error message display |
If customErrorTemplate is provided, it will be used to render the error message. The template receives an errorMessage context variable containing the error text.
> Limitation:
> Dynamic form changes (adding or removing controls at runtime) are not automatically handled in this version.
> If you add or remove controls after initialization, you must manually re-run the error setup logic (e.g., by calling the directive's setup method again).
> Support for automatic handling of dynamic form changes is planned for a future release.
Running unit tests
Run nx test spider-baby-utils-forms` to execute the unit tests.