1 import { Component, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';
2 import { FormControl, ValidatorFn } from '@angular/forms';
4 import { I18n } from '@ngx-translate/i18n-polyfill';
5 import * as _ from 'lodash';
7 import { CdFormGroup } from '../../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({}, this.i18n);
26 selectionLimit: number;
30 customBadgeValidators: ValidatorFn[] = [];
33 selection = new EventEmitter();
38 filteredOptions: Array<SelectOption> = [];
40 constructor(private i18n: I18n) {}
44 if (this.data.length > 0) {
45 this.initMissingOptions();
47 this.options = _.sortBy(this.options, ['name']);
51 private initFilter() {
52 this.filter = new FormControl('', { validators: this.customBadgeValidators });
53 this.form = new CdFormGroup({ filter: this.filter });
54 this.filteredOptions = [...(this.options || [])];
57 private initMissingOptions() {
58 const options = this.options.map((option) => option.name);
59 const needToCreate = this.data.filter((option) => options.indexOf(option) === -1);
60 needToCreate.forEach((option) => this.addOption(option));
61 this.forceOptionsToReflectData();
64 private addOption(name: string) {
65 this.options.push(new SelectOption(false, name, ''));
66 this.options = _.sortBy(this.options, ['name']);
67 this.triggerSelection(this.options.find((option) => option.name === name));
70 triggerSelection(option: SelectOption) {
73 (this.selectionLimit && !option.selected && this.data.length >= this.selectionLimit)
77 option.selected = !option.selected;
79 this.selection.emit({ option: option });
82 private updateOptions() {
83 this.data.splice(0, this.data.length);
84 this.options.forEach((option: SelectOption) => {
85 if (option.selected) {
86 this.data.push(option.name);
93 this.filteredOptions = this.options.filter((option) => option.name.includes(this.filter.value));
96 private forceOptionsToReflectData() {
97 this.options.forEach((option) => {
98 if (this.data.indexOf(option.name) !== -1) {
99 option.selected = true;
108 if (!this.options || !this.data || this.data.length === 0) {
111 this.forceOptionsToReflectData();
115 if (this.filteredOptions.length === 0) {
116 this.addCustomOption();
118 this.triggerSelection(this.filteredOptions[0]);
124 if (!this.isCreatable()) {
127 this.addOption(this.filter.value);
135 this.filter.value.length > 0 &&
136 this.filteredOptions.every((option) => option.name !== this.filter.value)
140 private resetFilter() {
141 this.filter.setValue('');
145 removeItem(item: string) {
146 this.triggerSelection(
147 this.options.find((option: SelectOption) => option.name === item && option.selected)