]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/shared-forms/select/select-custom-value.component.ts
Merge branch 'develop' into shorter-URLs-channels-accounts
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-forms / select / select-custom-value.component.ts
CommitLineData
ead64cdf
C
1import { Component, forwardRef, Input, OnChanges } from '@angular/core'
2import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
21e493d4 3import { 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})
17export 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}