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