diff options
Diffstat (limited to 'client/src/app/shared/shared-forms/select/select-custom-value.component.ts')
-rw-r--r-- | client/src/app/shared/shared-forms/select/select-custom-value.component.ts | 76 |
1 files changed, 76 insertions, 0 deletions
diff --git a/client/src/app/shared/shared-forms/select/select-custom-value.component.ts b/client/src/app/shared/shared-forms/select/select-custom-value.component.ts new file mode 100644 index 000000000..a8e5ad0d3 --- /dev/null +++ b/client/src/app/shared/shared-forms/select/select-custom-value.component.ts | |||
@@ -0,0 +1,76 @@ | |||
1 | import { Component, forwardRef, Input, OnChanges } from '@angular/core' | ||
2 | import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms' | ||
3 | import { SelectOptionsItem } from './select-options.component' | ||
4 | |||
5 | @Component({ | ||
6 | selector: 'my-select-custom-value', | ||
7 | styleUrls: [ './select-shared.component.scss' ], | ||
8 | templateUrl: './select-custom-value.component.html', | ||
9 | providers: [ | ||
10 | { | ||
11 | provide: NG_VALUE_ACCESSOR, | ||
12 | useExisting: forwardRef(() => SelectCustomValueComponent), | ||
13 | multi: true | ||
14 | } | ||
15 | ] | ||
16 | }) | ||
17 | export class SelectCustomValueComponent implements ControlValueAccessor, OnChanges { | ||
18 | @Input() items: SelectOptionsItem[] = [] | ||
19 | @Input() clearable = false | ||
20 | @Input() searchable = false | ||
21 | @Input() groupBy: string | ||
22 | @Input() labelForId: string | ||
23 | |||
24 | customValue: number | string = '' | ||
25 | selectedId: number | string | ||
26 | |||
27 | itemsWithCustom: SelectOptionsItem[] = [] | ||
28 | |||
29 | ngOnChanges () { | ||
30 | this.itemsWithCustom = this.getItems() | ||
31 | } | ||
32 | |||
33 | propagateChange = (_: any) => { /* empty */ } | ||
34 | |||
35 | writeValue (id: number | string) { | ||
36 | this.selectedId = id | ||
37 | |||
38 | if (this.isSelectedIdInItems() !== true) { | ||
39 | this.selectedId = 'other' | ||
40 | this.customValue = id | ||
41 | } | ||
42 | } | ||
43 | |||
44 | registerOnChange (fn: (_: any) => void) { | ||
45 | this.propagateChange = fn | ||
46 | } | ||
47 | |||
48 | registerOnTouched () { | ||
49 | // Unused | ||
50 | } | ||
51 | |||
52 | onModelChange () { | ||
53 | if (this.selectedId === 'other') { | ||
54 | return this.propagateChange(this.customValue) | ||
55 | } | ||
56 | |||
57 | return this.propagateChange(this.selectedId) | ||
58 | } | ||
59 | |||
60 | isSelectedIdInItems () { | ||
61 | return !!this.items.find(i => i.id === this.selectedId) | ||
62 | } | ||
63 | |||
64 | getItems () { | ||
65 | const other: SelectOptionsItem = { | ||
66 | id: 'other', | ||
67 | label: $localize`Custom value...` | ||
68 | } | ||
69 | |||
70 | return this.items.concat([ other ]) | ||
71 | } | ||
72 | |||
73 | isCustomValue () { | ||
74 | return this.selectedId === 'other' | ||
75 | } | ||
76 | } | ||