Open History to see the last commit
1import {
2 ChangeDetectorRef,
3 Directive,
4 effect,
5 inject,
6 input,
7} from '@angular/core'
8import { InternalFormGroupApi } from '@tanstack/form-core/internals'
9import type {
10 DeepKeys,
11 DeepValue,
12 FormGroupOptions,
13 FormGroupSubmitFn,
14 FormGroupValidators,
15 FormValidators,
16 ToFormErrorTypes,
17} from '@tanstack/form-core'
18import type { InternalFormApi } from '@tanstack/form-core/internals'
19β
20@Directive({
21 selector: '[tanstackFormGroup]',
22 standalone: true,
23 exportAs: 'formGroup',
24})
25export class TanStackFormGroup<
26 TFormData,
27 const TGroupName extends DeepKeys<TFormData>,
28 TGroupValue extends DeepValue<TFormData, TGroupName>,
29 const TGroupValidators extends FormGroupValidators<TGroupValue>,
30 const TFormValidators extends FormValidators<TFormData>,
31 TSubmitReturn,
32> {
33 tanstackFormGroup =
34 input.required<InternalFormApi<TFormData, TFormValidators, TSubmitReturn>>()
35 name = input.required<TGroupName>()
36 validators = input<NoInfer<TGroupValidators>>()
37 onSubmit =
38 input<
39 FormGroupSubmitFn<
40 TFormData,
41 TGroupName,
42 TGroupValue,
43 TGroupValidators,
44 ToFormErrorTypes<TFormValidators, TSubmitReturn>
45 >
46 >()
47 onSubmitInvalid =
48 input<
49 FormGroupOptions<
50 TFormData,
51 TGroupName,
52 TGroupValue,
53 TGroupValidators,
54 ToFormErrorTypes<TFormValidators, TSubmitReturn>
55 >['onSubmitInvalid']
56 >()
57β
58 private readonly changeDetector = inject(ChangeDetectorRef)
59 private group: InternalFormGroupApi<
60 TFormData,
61 TGroupName,
62 TGroupValue,
63 TGroupValidators,
64 ToFormErrorTypes<TFormValidators, TSubmitReturn>
65 > | null = null
66β
67 private getOptions() {
68 return {
69 form: this.tanstackFormGroup(),
70 name: this.name(),
71 validators: this.validators(),
72 onSubmit: this.onSubmit(),
73 onSubmitInvalid: this.onSubmitInvalid(),
74 }
75 }
76β
77 get api() {
78 if (!this.group) {
79 this.group = new InternalFormGroupApi(this.getOptions() as never)
80 }
81 return this.group
82 }
83β
84 constructor() {
85 effect(() => this.api.update(this.getOptions() as never))
86β
87 effect((onCleanup) => {
88 const group = this.api
89 group.mount()
90 onCleanup(() => group._cleanup())
91 })
92β
93 effect((onCleanup) => {
94 const subscription = this.api.atom.subscribe(() => {
95 this.changeDetector.markForCheck()
96 })
97 onCleanup(() => subscription.unsubscribe())
98 })
99 }
100}