1 import { Component, forwardRef, Input, OnChanges } from '@angular/core'
2 import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
3 import { SelectOptionsItem } from '../../../../types/select-options-item.model'
6 selector: 'my-select-custom-value',
7 styleUrls: [ './select-shared.component.scss' ],
8 templateUrl: './select-custom-value.component.html',
11 provide: NG_VALUE_ACCESSOR,
12 useExisting: forwardRef(() => SelectCustomValueComponent),
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 @Input() inputSuffix: string
24 @Input() inputType = 'text'
26 customValue: number | string = ''
27 selectedId: number | string
29 itemsWithCustom: SelectOptionsItem[] = []
32 this.itemsWithCustom = this.getItems()
35 propagateChange = (_: any) => { /* empty */ }
37 writeValue (id: number | string) {
40 if (this.isSelectedIdInItems() !== true) {
41 this.selectedId = 'other'
46 registerOnChange (fn: (_: any) => void) {
47 this.propagateChange = fn
50 registerOnTouched () {
55 if (this.selectedId === 'other') {
56 return this.propagateChange(this.customValue)
59 return this.propagateChange(this.selectedId)
62 isSelectedIdInItems () {
63 return !!this.items.find(i => i.id === this.selectedId)
67 const other: SelectOptionsItem = {
69 label: $localize`Custom value...`
72 return this.items.concat([ other ])
76 return this.selectedId === 'other'