1 import { Component, Input, forwardRef, OnInit } from '@angular/core'
2 import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'
3 import { SelectOptionsItem } from './select-options.component'
4 import { I18n } from '@ngx-translate/i18n-polyfill'
6 export type ItemSelectCheckboxValue = { id?: string | number, group?: string } | string
9 selector: 'my-select-checkbox',
10 styleUrls: [ './select-shared.component.scss', 'select-checkbox.component.scss' ],
11 templateUrl: './select-checkbox.component.html',
14 provide: NG_VALUE_ACCESSOR,
15 useExisting: forwardRef(() => SelectCheckboxComponent),
20 export class SelectCheckboxComponent implements OnInit, ControlValueAccessor {
21 @Input() availableItems: SelectOptionsItem[] = []
22 @Input() selectedItems: ItemSelectCheckboxValue[] = []
23 @Input() selectableGroup: boolean
24 @Input() selectableGroupAsModel: boolean
25 @Input() maxSelectedItems: number
26 @Input() placeholder: string
33 if (!this.placeholder) this.placeholder = this.i18n('Add a new option')
36 propagateChange = (_: any) => { /* empty */ }
38 writeValue (items: ItemSelectCheckboxValue[]) {
39 if (Array.isArray(items)) {
40 this.selectedItems = items.map(i => {
41 if (typeof i === 'string' || typeof i === 'number') {
46 return { group: i.group }
49 return { id: i.id + '' }
52 this.selectedItems = items
55 this.propagateChange(this.selectedItems)
58 registerOnChange (fn: (_: any) => void) {
59 this.propagateChange = fn
62 registerOnTouched () {
67 this.propagateChange(this.selectedItems)
70 compareFn (item: SelectOptionsItem, selected: ItemSelectCheckboxValue) {
71 if (typeof selected === 'string') {
72 return item.id === selected
75 if (this.selectableGroup && item.group && selected.group) {
76 return item.group === selected.group
79 if (selected.id && item.id) {
80 return item.id === selected.id