]>
Commit | Line | Data |
---|---|---|
66357162 C |
1 | import { Component, forwardRef, Input, OnInit } from '@angular/core' |
2 | import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms' | |
52c4976f C |
3 | import { SelectOptionsItem } from './select-options.component' |
4 | ||
5 | export type ItemSelectCheckboxValue = { id?: string | number, group?: string } | string | |
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 | |
24 | @Input() maxSelectedItems: number | |
857961f0 RK |
25 | @Input() placeholder: string |
26 | ||
857961f0 | 27 | ngOnInit () { |
66357162 | 28 | if (!this.placeholder) this.placeholder = $localize`Add a new option` |
857961f0 | 29 | } |
52c4976f C |
30 | |
31 | propagateChange = (_: any) => { /* empty */ } | |
32 | ||
33 | writeValue (items: ItemSelectCheckboxValue[]) { | |
34 | if (Array.isArray(items)) { | |
35 | this.selectedItems = items.map(i => { | |
36 | if (typeof i === 'string' || typeof i === 'number') { | |
37 | return i + '' | |
38 | } | |
39 | ||
40 | if (i.group) { | |
41 | return { group: i.group } | |
42 | } | |
43 | ||
44 | return { id: i.id + '' } | |
45 | }) | |
46 | } else { | |
47 | this.selectedItems = items | |
48 | } | |
49 | ||
50 | this.propagateChange(this.selectedItems) | |
51 | } | |
52 | ||
53 | registerOnChange (fn: (_: any) => void) { | |
54 | this.propagateChange = fn | |
55 | } | |
56 | ||
57 | registerOnTouched () { | |
58 | // Unused | |
59 | } | |
60 | ||
61 | onModelChange () { | |
62 | this.propagateChange(this.selectedItems) | |
63 | } | |
64 | ||
65 | compareFn (item: SelectOptionsItem, selected: ItemSelectCheckboxValue) { | |
66 | if (typeof selected === 'string') { | |
67 | return item.id === selected | |
68 | } | |
69 | ||
70 | if (this.selectableGroup && item.group && selected.group) { | |
71 | return item.group === selected.group | |
72 | } | |
73 | ||
74 | if (selected.id && item.id) { | |
75 | return item.id === selected.id | |
76 | } | |
77 | ||
78 | return false | |
79 | } | |
80 | } |