]>
Commit | Line | Data |
---|---|---|
ead64cdf C |
1 | import { Component, forwardRef, Input, OnChanges } from '@angular/core' |
2 | import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms' | |
21e493d4 | 3 | import { SelectOptionsItem } from '../../../../types/select-options-item.model' |
ead64cdf C |
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 | |
21e493d4 C |
23 | @Input() inputSuffix: string |
24 | @Input() inputType = 'text' | |
ead64cdf C |
25 | |
26 | customValue: number | string = '' | |
27 | selectedId: number | string | |
8d8a037e | 28 | disabled = false |
ead64cdf C |
29 | |
30 | itemsWithCustom: SelectOptionsItem[] = [] | |
31 | ||
32 | ngOnChanges () { | |
33 | this.itemsWithCustom = this.getItems() | |
34 | } | |
35 | ||
36 | propagateChange = (_: any) => { /* empty */ } | |
37 | ||
38 | writeValue (id: number | string) { | |
39 | this.selectedId = id | |
40 | ||
41 | if (this.isSelectedIdInItems() !== true) { | |
42 | this.selectedId = 'other' | |
43 | this.customValue = id | |
44 | } | |
45 | } | |
46 | ||
47 | registerOnChange (fn: (_: any) => void) { | |
48 | this.propagateChange = fn | |
49 | } | |
50 | ||
51 | registerOnTouched () { | |
52 | // Unused | |
53 | } | |
54 | ||
55 | onModelChange () { | |
56 | if (this.selectedId === 'other') { | |
57 | return this.propagateChange(this.customValue) | |
58 | } | |
59 | ||
60 | return this.propagateChange(this.selectedId) | |
61 | } | |
62 | ||
63 | isSelectedIdInItems () { | |
64 | return !!this.items.find(i => i.id === this.selectedId) | |
65 | } | |
66 | ||
67 | getItems () { | |
68 | const other: SelectOptionsItem = { | |
69 | id: 'other', | |
70 | label: $localize`Custom value...` | |
71 | } | |
72 | ||
73 | return this.items.concat([ other ]) | |
74 | } | |
75 | ||
76 | isCustomValue () { | |
77 | return this.selectedId === 'other' | |
78 | } | |
8d8a037e JB |
79 | |
80 | setDisabledState (isDisabled: boolean) { | |
81 | this.disabled = isDisabled | |
82 | } | |
ead64cdf | 83 | } |