Open History to see the last commit
1import { ChangeDetectorRef, DestroyRef, effect, inject } from '@angular/core'
2import { injectSelector } from '@tanstack/angular-store'
3import { InternalFormApi } from '@tanstack/form-core/internals'
4import type { FormOptions, FormValidators } from '@tanstack/form-core'
5β
6/**
7 * Creates and mounts a form in the current Angular injection context.
8 *
9 * `defaultValues` establish the initial state and inferred form value type.
10 * Form state changes notify Angular change detection, including OnPush
11 * components, and the form is cleaned up when the injection context is
12 * destroyed.
13 *
14 * Call this in a component field initializer, constructor, provider factory,
15 * or another active injection context.
16 *
17 * @example
18 * ```ts
19 * @Component({
20 * selector: 'app-profile-form',
21 * template: `<form></form>`,
22 * })
23 * class ProfileFormComponent {
24 * form = injectForm({
25 * defaultValues: { name: '' },
26 * onSubmit: ({ value }) => saveProfile(value),
27 * })
28 * }
29 * ```
30 *
31 * @param options - The initial form options. `defaultValues` drive form value
32 * inference.
33 * @returns The mounted form API registered for injection-context cleanup.
34 * @typeParam TFormData - Library-managed. Do not specify explicitly.
35 * @typeParam TFormValidators - Library-managed. Do not specify explicitly.
36 * @typeParam TSubmitReturn - Library-managed. Do not specify explicitly.
37 */
38export function injectForm<
39 TFormData,
40 const TFormValidators extends FormValidators<TFormData>,
41 TSubmitReturn,
42>(options: FormOptions<TFormData, TFormValidators, TSubmitReturn, unknown>) {
43 const form = new InternalFormApi<TFormData, TFormValidators, TSubmitReturn>(
44 options,
45 )
46 const destroyRef = inject(DestroyRef)
47 const changeDetector = inject(ChangeDetectorRef, { optional: true })
48 const state = injectSelector(form.atom)
49β
50 const unmount = form.mount()
51 destroyRef.onDestroy(unmount)
52β
53 // Form state is exposed as plain getters by form-core. Bridge its atom to
54 // Angular change detection so reads such as `form.state.canSubmit` update in
55 // OnPush templates without requiring a separate selector.
56 effect(() => {
57 state()
58 changeDetector?.markForCheck()
59 })
60β
61 return form
62}