Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/app/field-info.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Directive, effect, inject, input, TemplateRef, ViewContainerRef } from '@angular/core';
import { FieldTree } from '@angular/forms/signals';
import { FIELD_INFO } from './form-props';

@Directive({
selector: '[fieldInfo]',
standalone: true,
})
export class FieldInfo {
readonly fieldInfo = input.required<FieldTree<unknown>>();
readonly #templateRef = inject(TemplateRef<{ $implicit: string; cssClass: string }>);
readonly #viewContainer = inject(ViewContainerRef);

constructor() {
effect(() => {
const field = this.fieldInfo()();
this.#viewContainer.clear();

let messages: { info: string; cssClass: 'info' | 'invalid' }[] = [];

if (field.pending()) {
messages = [{ info: 'Checking availability ...', cssClass: 'info' }];
} else if (field.touched() && field.errors().length > 0) {
messages = field.errors().map((e) => ({ info: e.message || 'Invalid', cssClass: 'info' }));
} else if (field.hasMetadata(FIELD_INFO)) {
messages = [{ info: field.metadata(FIELD_INFO)!, cssClass: 'info' }];
}

messages.forEach((message) => {
this.#viewContainer.createEmbeddedView(this.#templateRef, {
$implicit: message.info,
cssClass: message.cssClass,
});
});
});
}
}
3 changes: 3 additions & 0 deletions src/app/form-props.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { createMetadataKey } from "@angular/forms/signals";

export const FIELD_INFO = createMetadataKey<string>()
30 changes: 12 additions & 18 deletions src/app/registration-form-3/registration-form-3.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ <h1>Version 3: Child Forms and Custom UI Controls</h1>
[field]="registrationForm.username"
[ariaInvalid]="ariaInvalidState(registrationForm.username)"
/>
@if (registrationForm.username().pending()) {
<small>Checking availability ...</small>
}
<app-form-error [fieldRef]="registrationForm.username" />
<small *fieldInfo="registrationForm.username; let message; let cssClass;" [class]="cssClass">{{ message }}</small>
</label>

<!-- A whole child form with own model -->
Expand All @@ -32,7 +29,7 @@ <h1>Version 3: Child Forms and Custom UI Controls</h1>
[field]="registrationForm.age"
[ariaInvalid]="ariaInvalidState(registrationForm.age)"
/>
<app-form-error [fieldRef]="registrationForm.age" />
<small *fieldInfo="registrationForm.age; let message; let cssClass" [class]="cssClass">{{ message }}</small>
</label>
</div>

Expand All @@ -45,7 +42,7 @@ <h1>Version 3: Child Forms and Custom UI Controls</h1>
[field]="registrationForm.password.pw1"
[ariaInvalid]="ariaInvalidState(registrationForm.password.pw1)"
/>
<app-form-error [fieldRef]="registrationForm.password.pw1" />
<small *fieldInfo="registrationForm.password.pw1; let message; let cssClass" [class]="cssClass">{{ message }}</small>
</label>
<label
>Password Confirmation
Expand All @@ -55,9 +52,9 @@ <h1>Version 3: Child Forms and Custom UI Controls</h1>
[field]="registrationForm.password.pw2"
[ariaInvalid]="ariaInvalidState(registrationForm.password.pw2)"
/>
<app-form-error [fieldRef]="registrationForm.password.pw2" />
<small *fieldInfo="registrationForm.password.pw2; let message; let cssClass" [class]="cssClass">{{ message }}</small>
</label>
<app-form-error [fieldRef]="registrationForm.password" />
<small *fieldInfo="registrationForm.password; let message; let cssClass" [class]="cssClass">{{ message }}</small>
</div>
<fieldset>
<legend>
Expand All @@ -76,11 +73,11 @@ <h1>Version 3: Child Forms and Custom UI Controls</h1>
/>
<button type="button" (click)="removeEmail($index)">-</button>
</div>
<app-form-error [fieldRef]="emailField" />
<small *fieldInfo="emailField; let message; let cssClass" [class]="cssClass">{{ message }}</small>
</div>
}
</div>
<app-form-error [fieldRef]="registrationForm.email" />
<small *fieldInfo="registrationForm.email; let message; let cssClass" [class]="cssClass">{{ message }}</small>
</fieldset>
<label
>Subscribe to Newsletter?
Expand All @@ -91,7 +88,7 @@ <h1>Version 3: Child Forms and Custom UI Controls</h1>
[selectOptions]="['Angular', 'React', 'Vue', 'Svelte']"
label="Topics (multiple possible):"
/>
<app-form-error [fieldRef]="registrationForm.newsletterTopics" />
<small *fieldInfo="registrationForm.newsletterTopics; let message; let cssClass" [class]="cssClass">{{ message }}</small>
<label
>I agree to the terms and conditions
<input
Expand All @@ -100,23 +97,20 @@ <h1>Version 3: Child Forms and Custom UI Controls</h1>
[field]="registrationForm.agreeToTermsAndConditions"
/>
</label>
<app-form-error [fieldRef]="registrationForm.agreeToTermsAndConditions" />
<small *fieldInfo="registrationForm.agreeToTermsAndConditions; let message; let cssClass" [class]="cssClass">{{ message }}</small>
<hr />
<app-form-error [fieldRef]="registrationForm" />
<small *fieldInfo="registrationForm; let message; let cssClass" [class]="cssClass">{{ message }}</small>
<div role="group">
<button
type="submit"
[disabled]="registrationForm().submitting()"
[ariaBusy]="registrationForm().submitting()"
>
@if (registrationForm().submitting()) {
Registering ...
} @else {
Register
}
@if (registrationForm().submitting()) { Registering ... } @else { Register }
</button>
<button type="reset" (click)="resetForm()">Reset</button>
</div>
</form>

<app-debug-output [form]="registrationForm"/>
<app-debug-output [form]="registrationForm" />
10 changes: 8 additions & 2 deletions src/app/registration-form-3/registration-form-3.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { Component, inject, resource, signal } from '@angular/core';
import { apply, applyEach, applyWhen, Field, disabled, email, FieldTree, form, maxLength, min, minLength, pattern, required, schema, submit, validate, validateAsync, validateTree, ValidationErrorWithField } from '@angular/forms/signals';
import { apply, applyEach, applyWhen, disabled, email, Field, FieldTree, form, maxLength, metadata, min, minLength, pattern, required, schema, submit, validate, validateAsync, validateTree, ValidationErrorWithField } from '@angular/forms/signals';

import { BackButton } from '../back-button/back-button';
import { DebugOutput } from '../debug-output/debug-output';
import { FieldInfo } from '../field-info';
import { FormError } from '../form-error/form-error';
import { GenderIdentity, IdentityForm, identitySchema, initialGenderIdentityState } from '../identity-form/identity-form';
import { Multiselect } from '../multiselect/multiselect';
import { RegistrationService } from '../registration-service';
import { FIELD_INFO } from '../form-props';

export interface RegisterFormData {
username: string;
Expand Down Expand Up @@ -59,9 +61,11 @@ export const formSchema = schema<RegisterFormData>((fieldPath) => {
},
onError: () => undefined
});
metadata(fieldPath.username, FIELD_INFO, () => "A username must consists of 3-12 characters.")

// Age validation
min(fieldPath.age, 18, { message: 'You must be >=18 years old.' });
metadata(fieldPath.age, FIELD_INFO, () => "You must be 18 years old to register")

// Terms and conditions
required(fieldPath.agreeToTermsAndConditions, {
Expand All @@ -80,6 +84,7 @@ export const formSchema = schema<RegisterFormData>((fieldPath) => {
applyEach(fieldPath.email, (emailPath) => {
email(emailPath, { message: 'E-Mail format is invalid' });
});
metadata(fieldPath.email, FIELD_INFO, () => "Please enter at least one valid E-Mail address")

// Password validation
required(fieldPath.password.pw1, { message: 'A password is required' });
Expand All @@ -103,6 +108,7 @@ export const formSchema = schema<RegisterFormData>((fieldPath) => {
message: 'The entered password must match with the one specified in "Password" field',
};
});
metadata(fieldPath.password, FIELD_INFO, () => "Please enter a password with min 8 characters and a special character.")

// Newsletter validation
applyWhen(
Expand All @@ -129,7 +135,7 @@ export const formSchema = schema<RegisterFormData>((fieldPath) => {

@Component({
selector: 'app-registration-form-3',
imports: [BackButton, Field, DebugOutput, FormError, IdentityForm, Multiselect],
imports: [BackButton, Field, DebugOutput, FormError, IdentityForm, Multiselect, FieldInfo],
templateUrl: './registration-form-3.html',
styleUrl: './registration-form-3.scss',
})
Expand Down