Open History to see the last commit
1import {
2 ChangeDetectionStrategy,
3 Component,
4 inject,
5 signal,
6} from '@angular/core'
7import {
8 FormField,
9 applyEach,
10 form,
11 minLength,
12 required,
13 submit as submitForm,
14 validateAsync,
15} from '@angular/forms/signals'
16import {
17 injectMutation,
18 injectQuery,
19 toResource,
20} from '@tanstack/angular-query'
21import { ValidationQueriesService } from './validation-queries.service'
22β
23@Component({
24 changeDetection: ChangeDetectionStrategy.OnPush,
25 selector: 'app-root',
26 imports: [FormField],
27 styleUrl: './app.component.css',
28 template: `
29 <main>
30 <h1>Username availability</h1>
31 <p>
32 Signal Forms uses a Resource backed by TanStack Query for async
33 validation. Try <code>taken</code> or any other username.
34 </p>
35β
36 <form (submit)="submit($event)">
37 <label>
38 Username
39 <input [formField]="registrationForm.username" />
40 </label>
41β
42 @if (registrationForm.username().pending()) {
43 <p class="checking">Checking availability...</p>
44 }
45β
46 @if (
47 registrationForm.username().touched() &&
48 registrationForm.username().invalid()
49 ) {
50 @for (error of registrationForm.username().errors(); track $index) {
51 <p class="error">{{ error.message }}</p>
52 }
53 }
54β
55 @if (
56 registrationForm.username().touched() &&
57 registrationForm.username().valid()
58 ) {
59 <p class="success">Username is available.</p>
60 }
61β
62 <p class="hint">
63 Invite-code validators are added with each array item. The query
64 resource does not exist until an invite code is added.
65 </p>
66β
67 <button type="button" (click)="addInviteCode()">Add invite code</button>
68β
69 @for (
70 inviteCode of registrationForm.inviteCodes;
71 track $index;
72 let index = $index
73 ) {
74 <div class="invite-code-row">
75 <label>
76 Invite code {{ index + 1 }}
77 <input [formField]="inviteCode" />
78 </label>
79β
80 <button type="button" (click)="removeInviteCode(index)">
81 Remove
82 </button>
83β
84 @if (inviteCode().pending()) {
85 <p class="checking">Checking invite code...</p>
86 }
87β
88 @if (inviteCode().touched() && inviteCode().invalid()) {
89 @for (error of inviteCode().errors(); track $index) {
90 <p class="error">{{ error.message }}</p>
91 }
92 }
93β
94 @if (inviteCode().touched() && inviteCode().valid()) {
95 <p class="success">Invite code is valid.</p>
96 }
97 </div>
98 }
99β
100 <button type="button" (click)="registrationForm().reloadValidation()">
101 Request validation again
102 </button>
103β
104 <button type="submit" [disabled]="registrationMutation.isPending()">
105 {{ registrationMutation.isPending() ? 'Saving...' : 'Submit' }}
106 </button>
107β
108 @if (registrationMutation.isError()) {
109 <p class="error">Could not submit the registration.</p>
110 }
111β
112 @if (
113 registrationMutation.isSuccess() && registrationMutation.data().ok
114 ) {
115 <p class="success">
116 Registration accepted for
117 <code>{{ registrationMutation.variables().username }}</code
118 >.
119 </p>
120 <p class="hint">
121 Mutation variables included
122 {{ registrationMutation.variables().inviteCodes.length }}
123 invite code(s).
124 </p>
125 }
126 </form>
127 </main>
128 `,
129})
130export class AppComponent {
131 private readonly queries = inject(ValidationQueriesService)
132 readonly model = signal({ username: '', inviteCodes: [] as Array<string> })
133 readonly registrationMutation = injectMutation(() =>
134 this.queries.submitRegistration(),
135 )
136β
137 readonly registrationForm = form(this.model, (path) => {
138 required(path.username, { message: 'Username is required' })
139 minLength(path.username, 3, {
140 message: 'Username must be at least 3 characters',
141 })
142β
143 validateAsync(path.username, {
144 debounce: 300,
145 params: ({ value }) => value().trim() || undefined,
146 factory: (username) => {
147 const query = injectQuery(() => {
148 const name = username() ?? ''
149 return {
150 ...this.queries.usernameAvailability(name),
151 enabled: !!name,
152 }
153 })
154β
155 return toResource(query)
156 },
157 onSuccess: (result) =>
158 result.available
159 ? null
160 : {
161 kind: 'usernameTaken',
162 message: 'Username is already taken',
163 },
164 onError: () => ({
165 kind: 'usernameUnavailable',
166 message: 'Could not check username availability',
167 }),
168 })
169β
170 applyEach(path.inviteCodes, (inviteCode) => {
171 required(inviteCode, { message: 'Invite code is required' })
172 minLength(inviteCode, 3, {
173 message: 'Invite code must be at least 3 characters',
174 })
175β
176 validateAsync(inviteCode, {
177 debounce: 300,
178 params: ({ value }) => value().trim() || undefined,
179 factory: (code) => {
180 const query = injectQuery(() => {
181 const value = code() ?? ''
182 return {
183 ...this.queries.inviteCodeValidation(value),
184 enabled: !!value,
185 }
186 })
187β
188 return toResource(query)
189 },
190 onSuccess: (result) =>
191 result.valid
192 ? null
193 : {
194 kind: 'invalidInviteCode',
195 message: 'Invite code must start with TEAM-',
196 },
197 onError: () => ({
198 kind: 'inviteCodeUnavailable',
199 message: 'Could not check the invite code',
200 }),
201 })
202 })
203 })
204β
205 addInviteCode() {
206 this.model.update((model) => ({
207 ...model,
208 inviteCodes: [...model.inviteCodes, ''],
209 }))
210 }
211β
212 removeInviteCode(index: number) {
213 this.model.update((model) => ({
214 ...model,
215 inviteCodes: model.inviteCodes.filter(
216 (_, itemIndex) => itemIndex !== index,
217 ),
218 }))
219 }
220β
221 async submit(event: SubmitEvent) {
222 event.preventDefault()
223β
224 const success = await submitForm(this.registrationForm, {
225 ignoreValidators: 'none',
226 action: async (field) => {
227 const result = await this.registrationMutation.mutateAsync(
228 field().value(),
229 )
230β
231 if (!result.ok) {
232 return result.errors.map((error) => ({
233 fieldTree:
234 error.fieldPath[0] === 'username'
235 ? this.registrationForm.username
236 : this.registrationForm.inviteCodes[error.fieldPath[1]],
237 kind: 'server',
238 message: error.error,
239 }))
240 }
241β
242 return undefined
243 },
244 })
245 if (success) {
246 this.model.set({ username: '', inviteCodes: [] })
247 }
248 }
249}