1 import { Component, Input, forwardRef } from '@angular/core'
2 import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'
3 import { SelectOptionsItem } from './select-options.component'
5 export type ItemSelectCheckboxValue = { id?: string | number, group?: string } | string
8 selector: 'my-select-checkbox',
9 styleUrls: [ './select-shared.component.scss', 'select-checkbox.component.scss' ],
10 templateUrl: './select-checkbox.component.html',
13 provide: NG_VALUE_ACCESSOR,
14 useExisting: forwardRef(() => SelectCheckboxComponent),
19 export class SelectCheckboxComponent implements ControlValueAccessor {
20 @Input() availableItems: SelectOptionsItem[] = []
21 @Input() selectedItems: ItemSelectCheckboxValue[] = []
22 @Input() selectableGroup: boolean
23 @Input() selectableGroupAsModel: boolean
24 @Input() maxSelectedItems: number
26 propagateChange = (_: any) => { /* empty */ }
28 writeValue (items: ItemSelectCheckboxValue[]) {
29 if (Array.isArray(items)) {
30 this.selectedItems = items.map(i => {
31 if (typeof i === 'string' || typeof i === 'number') {
36 return { group: i.group }
39 return { id: i.id + '' }
42 this.selectedItems = items
45 this.propagateChange(this.selectedItems)
48 registerOnChange (fn: (_: any) => void) {
49 this.propagateChange = fn
52 registerOnTouched () {
57 this.propagateChange(this.selectedItems)
60 compareFn (item: SelectOptionsItem, selected: ItemSelectCheckboxValue) {
61 if (typeof selected === 'string') {
62 return item.id === selected
65 if (this.selectableGroup && item.group && selected.group) {
66 return item.group === selected.group
69 if (selected.id && item.id) {
70 return item.id === selected.id