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```tsx
44const { value, error, touched, isValidating } = field.state
45```
46β
47There are three field states can be very useful to see how the user interacts with a field. A field is _"touched"_ when the user clicks/tabs into it, _"pristine"_ until the user changes value in it, and _"dirty"_ after the value has been changed. You can check these states via the `isTouched`, `isPristine` and `isDirty` flags, as seen below.
48β
49```tsx
50const { isTouched, isPristine, isDirty } = field.state.meta
51```
52β
53
54β
55## Field API
56β
57The 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.
58β
59Example:
60β
61```angular-html
62<input
63 [value]="fieldName.api.state.value"
64 (blur)="fieldName.api.handleBlur()"
65 (input)="fieldName.api.handleChange($any($event).target.value)"
66/>
67```
68β
69## Validation
70β
71`@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.
72β
73Example:
74β
75```angular-ts
76@Component({
77 selector: 'app-root',
78 standalone: true,
79 imports: [TanStackField],
80 template: `
81 <ng-container [tanstackField]="form" name="firstName" #firstName="field">
82 <input
83 [value]="firstName.api.state.value"
84 (blur)="firstName.api.handleBlur()"
85 (input)="firstName.api.handleChange($any($event).target.value)"
86 />
87 </ng-container>
88 `,
89})
90export class AppComponent {
91 firstNameValidator: FieldValidateFn<any, any, any, any, string> = ({
92 value,
93 }) =>
94 !value
95 ? 'A first name is required'
96 : value.length < 3
97 ? 'First name must be at least 3 characters'
98 : undefined
99β
100 firstNameAsyncValidator: FieldValidateAsyncFn<any, any, any, any, string> =
101 async ({ value }) => {
102 await new Promise((resolve) => setTimeout(resolve, 1000))
103 return value.includes('error') && 'No "error" allowed in first name'
104 }
105β
106 form = injectForm({
107 defaultValues: {
108 firstName: '',
109 },
110 onSubmit({ value }) {
111 console.log(value)
112 },
113 })
114}
115```
116β
117## Validation Adapters
118β
119In addition to hand-rolled validation options, we also provide adapters like `@tanstack/zod-form-adapter`, `@tanstack/yup-form-adapter`, and `@tanstack/valibot-form-adapter` to enable usage with common schema validation tools like [Zod](https://zod.dev/), [Yup](https://github.com/jquense/yup), and [Valibot](https://valibot.dev/).
120β
121Example:
122β
123```angular-ts
124import { zodValidator } from '@tanstack/zod-form-adapter'
125import { z } from 'zod'
126β
127@Component({
128 selector: 'app-root',
129 standalone: true,
130 imports: [TanStackField],
131 template: `
132 <ng-container
133 [tanstackField]="form"
134 name="firstName"
135 [validatorAdapter]="zodValidator()"
136 [validators]="{
137 onChange: z.string().min(3, 'First name must be at least 3 characters'),
138 onChangeAsyncDebounceMs: 500,
139 onChangeAsync: firstNameAsyncValidator
140 }"
141 #firstName="field"
142 >
143 <!-- ... -->
144 </ng-container>
145 `,
146})
147export class AppComponent {
148 firstNameAsyncValidator = z.string().refine(
149 async (value) => {
150 await new Promise((resolve) => setTimeout(resolve, 1000))
151 return !value.includes('error')
152 },
153 {
154 message: "No 'error' allowed in first name",
155 },
156 )
157β
158 form = injectForm({
159 defaultValues: {
160 firstName: '',
161 },
162 onSubmit({ value }) {
163 // Do something with form data
164 console.log(value)
165 },
166 })
167β
168 z = z
169 zodValidator = zodValidator
170}
171```
172β
173## Reactivity
174β
175`@tanstack/angular-form` offers a way to subscribe to form and field state changes via `injectStore(this.form, selector)`.
176β
177Example:
178β
179```typescript
180import { injectForm, injectStore } from '@tanstack/angular-form'
181β
182@Component(/*...*/)
183class AppComponent {
184 form = injectForm(/*...*/);
185 canSubmit = injectStore(this.form, (state) => state.canSubmit)
186 isSubmitting = injectStore(this.form, (state) => state.isSubmitting)
187}
188```
189β
190## Array Fields
191β
192Array 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.
193β
194When working with array fields, you can use the fields `pushValue`, `removeValue`, and `swapValues` methods to add, remove, and swap values in the array.
195β
196Example:
197β
198```angular-ts
199@Component({
200 selector: 'app-root',
201 standalone: true,
202 imports: [TanStackField],
203 template: `
204 <ng-container [tanstackField]="form" name="hobbies" #hobbies="field">
205 <div>
206 Hobbies
207 <div>
208 @if (!hobbies.api.state.value.length) {
209 No hobbies found
210 }
211 @for (_ of hobbies.api.state.value; track $index) {
212 <div>
213 <ng-container
214 [tanstackField]="form"
215 [name]="getHobbyName($index)"
216 #hobbyName="field"
217 >
218 <div>
219 <label [for]="hobbyName.api.name">Name:</label>
220 <input
221 [id]="hobbyName.api.name"
222 [name]="hobbyName.api.name"
223 [value]="hobbyName.api.state.value"
224 (blur)="hobbyName.api.handleBlur()"
225 (input)="
226 hobbyName.api.handleChange($any($event).target.value)
227 "
228 />
229 <button
230 type="button"
231 (click)="hobbies.api.removeValue($index)"
232 >
233 X
234 </button>
235 </div>
236 </ng-container>
237 <ng-container
238 [tanstackField]="form"
239 [name]="getHobbyDesc($index)"
240 #hobbyDesc="field"
241 >
242 <div>
243 <label [for]="hobbyDesc.api.name">Description:</label>
244 <input
245 [id]="hobbyDesc.api.name"
246 [name]="hobbyDesc.api.name"
247 [value]="hobbyDesc.api.state.value"
248 (blur)="hobbyDesc.api.handleBlur()"
249 (input)="
250 hobbyDesc.api.handleChange($any($event).target.value)
251 "
252 />
253 </div>
254 </ng-container>
255 </div>
256 }
257 </div>
258 <button type="button" (click)="hobbies.api.pushValue(defaultHobby)">
259 Add hobby
260 </button>
261 </div>
262 </ng-container>
263 `,
264})
265export class AppComponent {
266 defaultHobby = {
267 name: '',
268 description: '',
269 yearsOfExperience: 0,
270 }
271β
272 getHobbyName = (idx: number) => `hobbies[${idx}].name` as const;
273 getHobbyDesc = (idx: number) => `hobbies[${idx}].description` as const;
274β
275 form = injectForm({
276 defaultValues: {
277 hobbies: [] as Array<{
278 name: string
279 description: string
280 yearsOfExperience: number
281 }>,
282 },
283 onSubmit({ value }) {
284 alert(JSON.stringify(value))
285 },
286 })
287}
288```
289β
290These 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.