1 import { Component, forwardRef, Input, OnInit } from '@angular/core'
2 import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
3 import { SelectOptionsItem } from '../../../../types/select-options-item.model'
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 OnInit, ControlValueAccessor {
20 @Input() availableItems: SelectOptionsItem[] = []
21 @Input() selectedItems: ItemSelectCheckboxValue[] = []
22 @Input() selectableGroup: boolean
23 @Input() selectableGroupAsModel: boolean
24 @Input() maxSelectedItems: number
25 @Input() placeholder: string
28 if (!this.placeholder) this.placeholder = $localize`Add a new option`
31 propagateChange = (_: any) => { /* empty */ }
33 writeValue (items: ItemSelectCheckboxValue[]) {
34 if (Array.isArray(items)) {
35 this.selectedItems = items.map(i => {
36 if (typeof i === 'string' || typeof i === 'number') {
41 return { group: i.group }
44 return { id: i.id + '' }
47 this.selectedItems = items
50 this.propagateChange(this.selectedItems)
53 registerOnChange (fn: (_: any) => void) {
54 this.propagateChange = fn
57 registerOnTouched () {
62 this.propagateChange(this.selectedItems)
65 compareFn (item: SelectOptionsItem, selected: ItemSelectCheckboxValue) {
66 if (typeof selected === 'string') {
67 return item.id === selected
70 if (this.selectableGroup && item.group && selected.group) {
71 return item.group === selected.group
74 if (selected.id && item.id) {
75 return item.id === selected.id