1 import { Component, forwardRef, Input } from '@angular/core'
2 import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
3 import { Notifier } from '@app/core'
4 import { SelectOptionsItem } from '../../../../types/select-options-item.model'
5 import { ItemSelectCheckboxValue } from './select-checkbox.component'
8 selector: 'my-select-checkbox-all',
9 styleUrls: [ './select-shared.component.scss' ],
13 [(ngModel)]="selectedItems"
14 (ngModelChange)="onModelChange()"
15 [availableItems]="availableItems"
16 [selectableGroup]="true" [selectableGroupAsModel]="true"
17 [placeholder]="placeholder"
20 </my-select-checkbox>`,
24 provide: NG_VALUE_ACCESSOR,
25 useExisting: forwardRef(() => SelectCheckboxAllComponent),
30 export class SelectCheckboxAllComponent implements ControlValueAccessor {
31 @Input() availableItems: SelectOptionsItem[] = []
32 @Input() allGroupLabel: string
34 @Input() placeholder: string
35 @Input() maxItems: number
37 selectedItems: ItemSelectCheckboxValue[]
40 private notifier: Notifier
45 propagateChange = (_: any) => { /* empty */ }
47 writeValue (items: string[]) {
48 this.selectedItems = items
49 ? items.map(l => ({ id: l }))
50 : [ { group: this.allGroupLabel } ]
53 registerOnChange (fn: (_: any) => void) {
54 this.propagateChange = fn
57 registerOnTouched () {
62 if (!this.isMaxConstraintValid()) return
64 this.propagateChange(this.buildOutputItems())
68 // Automatically use "All languages" if the user did not select any language
69 if (Array.isArray(this.selectedItems) && this.selectedItems.length === 0) {
70 this.selectedItems = [ { group: this.allGroupLabel } ]
74 private isMaxConstraintValid () {
75 if (!this.maxItems) return true
77 const outputItems = this.buildOutputItems()
78 if (!outputItems) return true
80 if (outputItems.length >= this.maxItems) {
81 this.notifier.error($localize`You can't select more than ${this.maxItems} items`)
89 private buildOutputItems () {
90 if (!Array.isArray(this.selectedItems)) return undefined
93 if (this.selectedItems.length === 0 || this.selectedItems.length === this.availableItems.length) {
97 if (this.selectedItems.length === 1) {
98 const item = this.selectedItems[0]
100 const itemGroup = typeof item === 'string' || typeof item === 'number'
104 if (itemGroup === this.allGroupLabel) return null
107 return this.selectedItems.map(l => {
108 if (typeof l === 'string' || typeof l === 'number') return l
110 if (l.group) return l.group