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