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

tanstack-field.directive.ts

90 lines2.4 KB

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