1 import { Component, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';
2 import { FormControl, ValidatorFn } from '@angular/forms';
4 import _ from 'lodash';
6 import { Icons } from '~/app/shared/enum/icons.enum';
7 import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
8 import { SelectMessages } from './select-messages.model';
9 import { SelectOption } from './select-option.model';
12 selector: 'cd-select',
13 templateUrl: './select.component.html',
14 styleUrls: ['./select.component.scss']
16 export class SelectComponent implements OnInit, OnChanges {
20 data: Array<string> = [];
22 options: Array<SelectOption> = [];
24 messages = new SelectMessages({});
26 selectionLimit: number;
30 customBadgeValidators: ValidatorFn[] = [];
33 selection = new EventEmitter();
38 filteredOptions: Array<SelectOption> = [];
43 if (this.data.length > 0) {
44 this.initMissingOptions();
46 this.options = _.sortBy(this.options, ['name']);
50 private initFilter() {
51 this.filter = new FormControl('', { validators: this.customBadgeValidators });
52 this.form = new CdFormGroup({ filter: this.filter });
53 this.filteredOptions = [...(this.options || [])];
56 private initMissingOptions() {
57 const options = this.options.map((option) => option.name);
58 const needToCreate = this.data.filter((option) => options.indexOf(option) === -1);
59 needToCreate.forEach((option) => this.addOption(option));
60 this.forceOptionsToReflectData();
63 private addOption(name: string) {
64 this.options.push(new SelectOption(false, name, ''));
65 this.options = _.sortBy(this.options, ['name']);
66 this.triggerSelection(this.options.find((option) => option.name === name));
69 triggerSelection(option: SelectOption) {
72 (this.selectionLimit && !option.selected && this.data.length >= this.selectionLimit)
76 option.selected = !option.selected;
78 this.selection.emit({ option: option });
81 private updateOptions() {
82 this.data.splice(0, this.data.length);
83 this.options.forEach((option: SelectOption) => {
84 if (option.selected) {
85 this.data.push(option.name);
92 this.filteredOptions = this.options.filter((option) => option.name.includes(this.filter.value));
95 private forceOptionsToReflectData() {
96 this.options.forEach((option) => {
97 if (this.data.indexOf(option.name) !== -1) {
98 option.selected = true;
107 if (!this.options || !this.data || this.data.length === 0) {
110 this.forceOptionsToReflectData();
114 if (this.filteredOptions.length === 0) {
115 this.addCustomOption();
117 this.triggerSelection(this.filteredOptions[0]);
123 if (!this.isCreatable()) {
126 this.addOption(this.filter.value);
134 this.filter.value.length > 0 &&
135 this.filteredOptions.every((option) => option.name !== this.filter.value)
139 private resetFilter() {
140 this.filter.setValue('');
144 removeItem(item: string) {
145 this.triggerSelection(
146 this.options.find((option: SelectOption) => option.name === item && option.selected)