Open History to see the last commit
1import {
2 Directive,
3 Input,
4 type OnChanges,
5 type OnDestroy,
6 type OnInit,
7 booleanAttribute,
8 numberAttribute,
9} from '@angular/core'
10import {
11 type DeepKeys,
12 type DeepValue,
13 FieldApi,
14 type FieldMeta,
15 type FieldOptions,
16 type FieldValidators,
17 FormApi,
18 type NoInfer as NoInferHack,
19 type Validator,
20} from '@tanstack/form-core'
21β
22@Directive({
23 selector: '[tanstackField]',
24 standalone: true,
25 exportAs: 'field',
26})
27export class TanStackField<
28 TParentData,
29 const TName extends DeepKeys<TParentData>,
30 TFieldValidator extends
31 | Validator<DeepValue<TParentData, TName>, unknown>
32 | undefined = undefined,
33 TFormValidator extends
34 | Validator<TParentData, unknown>
35 | undefined = undefined,
36 TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,
37 >
38 implements
39 OnInit,
40 OnChanges,
41 OnDestroy,
42 FieldOptions<TParentData, TName, TFieldValidator, TFormValidator, TData>
43{
44 @Input({ required: true }) name!: TName
45 // Setting as NoInferHack as it's the same internal type cast as TanStack Form Core
46 // This can be removed when TanStack Form Core is moved to TS min of 5.4
47 // and the NoInfer internal util type is rm-rf'd
48 @Input() defaultValue?: NoInferHack<TData>
49 @Input({ transform: numberAttribute }) asyncDebounceMs?: number
50 @Input({ transform: booleanAttribute }) asyncAlways?: boolean
51 @Input() validatorAdapter?: TFieldValidator
52 @Input({ required: true }) tanstackField!: FormApi<
53 TParentData,
54 TFormValidator
55 >
56 @Input() validators?: NoInfer<
57 FieldValidators<TParentData, TName, TFieldValidator, TFormValidator, TData>
58 >
59 @Input() defaultMeta?: Partial<FieldMeta>
60β
61 api!: FieldApi<TParentData, TName, TFieldValidator, TFormValidator, TData>
62β
63 private getOptions() {
64 return {
65 defaultValue: this.defaultValue,
66 asyncDebounceMs: this.asyncDebounceMs,
67 asyncAlways: this.asyncAlways,
68 validatorAdapter: this.validatorAdapter,
69 validators: this.validators,
70 defaultMeta: this.defaultMeta,
71 name: this.name,
72 form: this.tanstackField,
73 }
74 }
75β
76 unmount?: () => void
77β
78 ngOnInit() {
79 this.api = new FieldApi(this.getOptions())
80β
81 this.unmount = this.api.mount()
82 }
83β
84 ngOnDestroy() {
85 this.unmount?.()
86 }
87β
88 ngOnChanges() {
89 const api = this.api as typeof this.api | undefined
90 if (!api) return
91 api.update(this.getOptions())
92 }
93}