Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

form-group.ts

99 lines2.4 KB

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