]>
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 | |
28 | ||
29 | itemsWithCustom: SelectOptionsItem[] = [] | |
30 | ||
31 | ngOnChanges () { | |
32 | this.itemsWithCustom = this.getItems() | |
33 | } | |
34 | ||
35 | propagateChange = (_: any) => { /* empty */ } | |
36 | ||
37 | writeValue (id: number | string) { | |
38 | this.selectedId = id | |
39 | ||
40 | if (this.isSelectedIdInItems() !== true) { | |
41 | this.selectedId = 'other' | |
42 | this.customValue = id | |
43 | } | |
44 | } | |
45 | ||
46 | registerOnChange (fn: (_: any) => void) { | |
47 | this.propagateChange = fn | |
48 | } | |
49 | ||
50 | registerOnTouched () { | |
51 | // Unused | |
52 | } | |
53 | ||
54 | onModelChange () { | |
55 | if (this.selectedId === 'other') { | |
56 | return this.propagateChange(this.customValue) | |
57 | } | |
58 | ||
59 | return this.propagateChange(this.selectedId) | |
60 | } | |
61 | ||
62 | isSelectedIdInItems () { | |
63 | return !!this.items.find(i => i.id === this.selectedId) | |
64 | } | |
65 | ||
66 | getItems () { | |
67 | const other: SelectOptionsItem = { | |
68 | id: 'other', | |
69 | label: $localize`Custom value...` | |
70 | } | |
71 | ||
72 | return this.items.concat([ other ]) | |
73 | } | |
74 | ||
75 | isCustomValue () { | |
76 | return this.selectedId === 'other' | |
77 | } | |
78 | } |