forked from tomalaforge/angular-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddress-form.component.ts
More file actions
98 lines (93 loc) · 2.52 KB
/
address-form.component.ts
File metadata and controls
98 lines (93 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { Component, input, model } from '@angular/core';
import {
FieldState,
FieldTree,
FormValueControl,
} from '@angular/forms/signals';
interface AddressFieldGroup {
street: string;
zipcode: string;
city: string;
}
@Component({
selector: 'app-address-form',
template: `
<div class="grid gap-4 sm:grid-cols-2" data-testid="shipping-fields">
<label
class="flex flex-col gap-1 text-sm font-medium text-slate-700 sm:col-span-2">
Street
<input
class="input"
type="text"
[value]="value().street"
(input)="updateField('street', $event.target.value)"
required
aria-required="true" />
<span class="hint">
@if (showError(fieldTree().street())) {
This field is required
}
</span>
</label>
<label class="flex flex-col gap-1 text-sm font-medium text-slate-700">
ZIP code
<input
class="input"
type="text"
[value]="value().zipcode"
(input)="updateField('zipcode', $event.target.value)"
required
aria-required="true" />
<span class="hint">
@if (showError(fieldTree().zipcode())) {
This field is required
}
</span>
</label>
<label class="flex flex-col gap-1 text-sm font-medium text-slate-700">
City
<input
class="input"
type="text"
[value]="value().city"
(input)="updateField('city', $event.target.value)"
required
aria-required="true" />
<span class="hint">
@if (showError(fieldTree().city())) {
This field is required
}
</span>
</label>
</div>
`,
styles: [
`
.input {
@apply w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm shadow-sm outline-none transition focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200;
}
.hint {
@apply text-xs text-rose-600;
}
`,
],
})
export class AddressFormComponent
implements FormValueControl<AddressFieldGroup>
{
value = model<AddressFieldGroup>({
street: '',
zipcode: '',
city: '',
});
fieldTree = input.required<FieldTree<AddressFieldGroup>>();
updateField(field: keyof AddressFieldGroup, value: string) {
this.value.update((state) => ({
...state,
[field]: value,
}));
}
showError<T>(field: FieldState<T>): boolean {
return field.invalid() && (field.touched() || field.dirty());
}
}