]>
Commit | Line | Data |
---|---|---|
66357162 C |
1 | import { Component, forwardRef, Input, OnInit } from '@angular/core' |
2 | import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms' | |
21e493d4 | 3 | import { SelectOptionsItem } from '../../../../types/select-options-item.model' |
52c4976f | 4 | |
dd24f1bb | 5 | export type ItemSelectCheckboxValue = { id?: string, group?: string } | string |
52c4976f C |
6 | |
7 | @Component({ | |
8 | selector: 'my-select-checkbox', | |
9 | styleUrls: [ './select-shared.component.scss', 'select-checkbox.component.scss' ], | |
10 | templateUrl: './select-checkbox.component.html', | |
11 | providers: [ | |
12 | { | |
13 | provide: NG_VALUE_ACCESSOR, | |
14 | useExisting: forwardRef(() => SelectCheckboxComponent), | |
15 | multi: true | |
16 | } | |
17 | ] | |
18 | }) | |
857961f0 | 19 | export class SelectCheckboxComponent implements OnInit, ControlValueAccessor { |
52c4976f C |
20 | @Input() availableItems: SelectOptionsItem[] = [] |
21 | @Input() selectedItems: ItemSelectCheckboxValue[] = [] | |
22 | @Input() selectableGroup: boolean | |
23 | @Input() selectableGroupAsModel: boolean | |
857961f0 RK |
24 | @Input() placeholder: string |
25 | ||
8d8a037e JB |
26 | disabled = false |
27 | ||
857961f0 | 28 | ngOnInit () { |
66357162 | 29 | if (!this.placeholder) this.placeholder = $localize`Add a new option` |
857961f0 | 30 | } |
52c4976f C |
31 | |
32 | propagateChange = (_: any) => { /* empty */ } | |
33 | ||
34 | writeValue (items: ItemSelectCheckboxValue[]) { | |
35 | if (Array.isArray(items)) { | |
36 | this.selectedItems = items.map(i => { | |
37 | if (typeof i === 'string' || typeof i === 'number') { | |
38 | return i + '' | |
39 | } | |
40 | ||
41 | if (i.group) { | |
42 | return { group: i.group } | |
43 | } | |
44 | ||
45 | return { id: i.id + '' } | |
46 | }) | |
47 | } else { | |
48 | this.selectedItems = items | |
49 | } | |
52c4976f C |
50 | } |
51 | ||
52 | registerOnChange (fn: (_: any) => void) { | |
53 | this.propagateChange = fn | |
54 | } | |
55 | ||
56 | registerOnTouched () { | |
57 | // Unused | |
58 | } | |
59 | ||
60 | onModelChange () { | |
61 | this.propagateChange(this.selectedItems) | |
62 | } | |
63 | ||
8d8a037e JB |
64 | setDisabledState (isDisabled: boolean) { |
65 | this.disabled = isDisabled | |
66 | } | |
67 | ||
52c4976f | 68 | compareFn (item: SelectOptionsItem, selected: ItemSelectCheckboxValue) { |
dd24f1bb | 69 | if (typeof selected === 'string' || typeof selected === 'number') { |
52c4976f C |
70 | return item.id === selected |
71 | } | |
72 | ||
73 | if (this.selectableGroup && item.group && selected.group) { | |
74 | return item.group === selected.group | |
75 | } | |
76 | ||
77 | if (selected.id && item.id) { | |
78 | return item.id === selected.id | |
79 | } | |
80 | ||
81 | return false | |
82 | } | |
83 | } |