Open History to see the last commit
1---
2id: basic-concepts
3title: Basic Concepts and Terminology
4---
5β
6This page introduces the basic concepts and terminology used in the `@tanstack/angular-form` library. Familiarizing yourself with these concepts will help you better understand and work with the library.
7β
8## Form Instance
9β
10A Form Instance is an object that represents an individual form and provides methods and properties for working with the form. You create a form instance using the `injectForm` function. The hook accepts an object with an `onSubmit` function, which is called when the form is submitted.
11β
12```typescript
13const form = injectForm({
14 onSubmit: async ({ value }) => {
15 // Do something with form data
16 console.log(value)
17 },
18})
19```
20β
21## Field
22β
23A Field represents a single form input element, such as a text input or a checkbox. Fields are created using the `tanstackField` directive. The directive accepts a name prop, which should match a key in the form's default values. It also exposes a `field` named instance of the directive's internals that should be used via a template variable to access the field's internals.
24β
25Example:
26β
27```html
28<ng-container [tanstackField]="form" name="firstName" #firstName="field">
29 <input
30 [value]="firstName.api.state.value"
31 (blur)="firstName.api.handleBlur()"
32 (input)="firstName.api.handleChange($any($event).target.value)"
33 />
34</ng-container>
35```
36β
37## Field State
38β
39Each field has its own state, which includes its current value, validation status, error messages, and other metadata. You can access a field's state using the `fieldApi.state` property.
40β
41Example:
42β
43```ts
44const {
45 value,
46 meta: { errors, isValidating },
47} = field.state
48```
49β
50There are four states in the metadata that can be useful to see how the user interacts with a field:
51β
52- _"isTouched"_, after the user changes the field or blurs the field
53- _"isDirty"_, after the field's value has been changed, even if it's been reverted to the default. Opposite of _"isPristine"_
54- _"isPristine"_, until the user changes the field value. Opposite of _"isDirty"_
55- _"isBlurred"_, after the field has been blurred
56β
57```ts
58const { isTouched, isDirty, isPristine, isBlurred } = field.state.meta
59```
60β
61
62β
63## Understanding 'isDirty' in Different Libraries
64β
65Non-Persistent `dirty` state
66β
67- **Libraries**: React Hook Form (RHF), Formik, Final Form.
68- **Behavior**: A field is 'dirty' if its value differs from the default. Reverting to the default value makes it 'clean' again.
69β
70Persistent `dirty` state
71β
72- **Libraries**: Angular Form, Vue FormKit.
73- **Behavior**: A field remains 'dirty' once changed, even if reverted to the default value.
74β
75We have chosen the persistent 'dirty' state model. To also support a non-persistent 'dirty' state, we introduce an additional flag:
76β
77- _"isDefaultValue"_, whether the field's current value is the default value
78β
79```ts
80const { isDefaultValue, isTouched } = field.state.meta
81β
82// The following line will re-create the non-Persistent `dirty` functionality.
83const nonPersistentIsDirty = !isDefaultValue
84```
85β
86
87β
88## Field API
89β
90The Field API is an object accessed in the `tanstackField.api` property when creating a field. It provides methods for working with the field's state.
91β
92Example:
93β
94```angular-html
95<input
96 [value]="fieldName.api.state.value"
97 (blur)="fieldName.api.handleBlur()"
98 (input)="fieldName.api.handleChange($any($event).target.value)"
99/>
100```
101β
102## Validation
103β
104`@tanstack/angular-form` provides both synchronous and asynchronous validation out of the box. Validation functions can be passed to the `tanstackField` directive using the `validators` prop.
105β
106Example:
107β
108```angular-ts
109@Component({
110 selector: 'app-root',
111 standalone: true,
112 imports: [TanStackField],
113 template: `
114 <ng-container [tanstackField]="form" name="firstName" #firstName="field">
115 <input
116 [value]="firstName.api.state.value"
117 (blur)="firstName.api.handleBlur()"
118 (input)="firstName.api.handleChange($any($event).target.value)"
119 />
120 </ng-container>
121 `,
122})
123export class AppComponent {
124 firstNameValidator: FieldValidateFn<any, any, string, any> = ({
125 value,
126 }) =>
127 !value
128 ? 'A first name is required'
129 : value.length < 3
130 ? 'First name must be at least 3 characters'
131 : undefined
132β
133 firstNameAsyncValidator: FieldValidateAsyncFn<any, string, any> =
134 async ({ value }) => {
135 await new Promise((resolve) => setTimeout(resolve, 1000))
136 return value.includes('error') && 'No "error" allowed in first name'
137 }
138β
139 form = injectForm({
140 defaultValues: {
141 firstName: '',
142 },
143 onSubmit({ value }) {
144 console.log(value)
145 },
146 })
147}
148```
149β
150## Validation with Standard Schema Libraries
151β
152In addition to hand-rolled validation options, we also support the [Standard Schema](https://github.com/standard-schema/standard-schema) specification.
153β
154You can define a schema using any of the libraries implementing the specification and pass it to a form or field validator.
155β
156Supported libraries include:
157β
158- [Zod](https://zod.dev/) (v3.24.0 or higher)
159- [Valibot](https://valibot.dev/) (v1.0.0 or higher)
160- [ArkType](https://arktype.io/) (v2.1.20 or higher)
161- [Yup](https://github.com/jquense/yup) (v1.7.0 or higher)
162β
163Example:
164β
165```angular-ts
166import { z } from 'zod'
167β
168@Component({
169 selector: 'app-root',
170 standalone: true,
171 imports: [TanStackField],
172 template: `
173 <ng-container
174 [tanstackField]="form"
175 name="firstName"
176 [validators]="{
177 onChange: z.string().min(3, 'First name must be at least 3 characters'),
178 onChangeAsyncDebounceMs: 500,
179 onChangeAsync: firstNameAsyncValidator
180 }"
181 #firstName="field"
182 >
183 <!-- ... -->
184 </ng-container>
185 `,
186})
187export class AppComponent {
188 firstNameAsyncValidator = z.string().refine(
189 async (value) => {
190 await new Promise((resolve) => setTimeout(resolve, 1000))
191 return !value.includes('error')
192 },
193 {
194 message: "No 'error' allowed in first name",
195 },
196 )
197β
198 form = injectForm({
199 defaultValues: {
200 firstName: '',
201 },
202 onSubmit({ value }) {
203 // Do something with form data
204 console.log(value)
205 },
206 })
207β
208 z = z
209}
210```
211β
212## Reactivity
213β
214`@tanstack/angular-form` offers a way to subscribe to form and field state changes via `injectStore(this.form, selector)`.
215β
216Example:
217β
218```typescript
219import { injectForm, injectStore } from '@tanstack/angular-form'
220β
221@Component(/*...*/)
222class AppComponent {
223 form = injectForm(/*...*/)
224 canSubmit = injectStore(this.form, (state) => state.canSubmit)
225 isSubmitting = injectStore(this.form, (state) => state.isSubmitting)
226}
227```
228β
229## Listeners
230β
231`@tanstack/angular-form` allows you to react to specific triggers and "listen" to them to dispatch side effects.
232β
233Example:
234β
235```angular-ts
236@Component({
237 selector: 'app-root',
238 standalone: true,
239 imports: [TanStackField],
240 template: `
241 <ng-container
242 [tanstackField]="form"
243 name="country"
244 [listeners]="{
245 onChange: onCountryChange
246 }"
247 #country="field"
248 ></ng-container>
249 `,
250})
251β
252...
253β
254onCountryChange: FieldListenerFn<any, any, any, any, string> = ({
255 value,
256 }) => {
257 console.log(`Country changed to: ${value}, resetting province`)
258 this.form.setFieldValue('province', '')
259 }
260```
261β
262More information can be found at [Listeners](./listeners.md)
263β
264## Array Fields
265β
266Array fields allow you to manage a list of values within a form, such as a list of hobbies. You can create an array field using the `tanstackField` directive.
267β
268When working with array fields, you can use the fields `pushValue`, `removeValue`, `swapValues` and `moveValue` methods to add, remove, swap, and move a value from one index to another within the array, respectively. Additional helper methods such as `insertValue`, `replaceValue`, and `clearValues` are also available for inserting, replacing, and clearing array values.
269β
270Example:
271β
272```angular-ts
273@Component({
274 selector: 'app-root',
275 standalone: true,
276 imports: [TanStackField],
277 template: `
278 <ng-container [tanstackField]="form" name="hobbies" #hobbies="field">
279 <div>
280 Hobbies
281 <div>
282 @if (!hobbies.api.state.value.length) {
283 No hobbies found
284 }
285 @for (_ of hobbies.api.state.value; track $index) {
286 <div>
287 <ng-container
288 [tanstackField]="form"
289 [name]="getHobbyName($index)"
290 #hobbyName="field"
291 >
292 <div>
293 <label [for]="hobbyName.api.name">Name:</label>
294 <input
295 [id]="hobbyName.api.name"
296 [name]="hobbyName.api.name"
297 [value]="hobbyName.api.state.value"
298 (blur)="hobbyName.api.handleBlur()"
299 (input)="
300 hobbyName.api.handleChange($any($event).target.value)
301 "
302 />
303 <button
304 type="button"
305 (click)="hobbies.api.removeValue($index)"
306 >
307 X
308 </button>
309 </div>
310 </ng-container>
311 <ng-container
312 [tanstackField]="form"
313 [name]="getHobbyDesc($index)"
314 #hobbyDesc="field"
315 >
316 <div>
317 <label [for]="hobbyDesc.api.name">Description:</label>
318 <input
319 [id]="hobbyDesc.api.name"
320 [name]="hobbyDesc.api.name"
321 [value]="hobbyDesc.api.state.value"
322 (blur)="hobbyDesc.api.handleBlur()"
323 (input)="
324 hobbyDesc.api.handleChange($any($event).target.value)
325 "
326 />
327 </div>
328 </ng-container>
329 </div>
330 }
331 </div>
332 <button type="button" (click)="hobbies.api.pushValue(defaultHobby)">
333 Add hobby
334 </button>
335 </div>
336 </ng-container>
337 `,
338})
339export class AppComponent {
340 defaultHobby = {
341 name: '',
342 description: '',
343 yearsOfExperience: 0,
344 }
345β
346 getHobbyName = (idx: number) => `hobbies[${idx}].name` as const;
347 getHobbyDesc = (idx: number) => `hobbies[${idx}].description` as const;
348β
349 form = injectForm({
350 defaultValues: {
351 hobbies: [] as Array<{
352 name: string
353 description: string
354 yearsOfExperience: number
355 }>,
356 },
357 onSubmit({ value }) {
358 alert(JSON.stringify(value))
359 },
360 })
361}
362```
363β
364These are the basic concepts and terminology used in the `@tanstack/angular-form` library. Understanding these concepts will help you work more effectively with the library and create complex forms with ease.