1 import { Component, Input, OnChanges, OnInit } from '@angular/core';
2 import { FormControl, ValidatorFn } from '@angular/forms';
4 import * as _ from 'lodash';
6 import { CdFormGroup } from '../../forms/cd-form-group';
7 import { SelectBadgesMessages } from './select-badges-messages.model';
8 import { SelectBadgesOption } from './select-badges-option.model';
11 selector: 'cd-select-badges',
12 templateUrl: './select-badges.component.html',
13 styleUrls: ['./select-badges.component.scss']
15 export class SelectBadgesComponent implements OnInit, OnChanges {
17 data: Array<string> = [];
19 options: Array<SelectBadgesOption> = [];
21 messages = new SelectBadgesMessages({});
23 selectionLimit: number;
27 customBadgeValidators: ValidatorFn[] = [];
31 filteredOptions: Array<SelectBadgesOption> = [];
37 if (this.data.length > 0) {
38 this.initMissingOptions();
40 this.options = _.sortBy(this.options, ['name']);
44 private initFilter() {
45 this.filter = new FormControl('', { validators: this.customBadgeValidators });
46 this.form = new CdFormGroup({ filter: this.filter });
47 this.filteredOptions = [...this.options];
50 private initMissingOptions() {
51 const options = this.options.map((option) => option.name);
52 const needToCreate = this.data.filter((option) => options.indexOf(option) === -1);
53 needToCreate.forEach((option) => this.addOption(option));
54 this.forceOptionsToReflectData();
57 private addOption(name: string) {
58 this.options.push(new SelectBadgesOption(false, name, ''));
59 this.options = _.sortBy(this.options, ['name']);
60 this.triggerSelection(this.options.find((option) => option.name === name));
63 triggerSelection(option: SelectBadgesOption) {
66 (this.selectionLimit && !option.selected && this.data.length >= this.selectionLimit)
70 option.selected = !option.selected;
74 private updateOptions() {
75 this.data.splice(0, this.data.length);
76 this.options.forEach((option: SelectBadgesOption) => {
77 if (option.selected) {
78 this.data.push(option.name);
85 this.filteredOptions = this.options.filter((option) => option.name.includes(this.filter.value));
88 private forceOptionsToReflectData() {
89 this.options.forEach((option) => {
90 if (this.data.indexOf(option.name) !== -1) {
91 option.selected = true;
97 if (!this.options || !this.data || this.data.length === 0) {
100 this.forceOptionsToReflectData();
104 if (this.filteredOptions.length === 0) {
105 this.addCustomOption();
107 this.triggerSelection(this.filteredOptions[0]);
113 if (!this.isCreatable()) {
116 this.addOption(this.filter.value);
124 this.filter.value.length > 0 &&
125 this.filteredOptions.every((option) => option.name !== this.filter.value)
129 private resetFilter() {
130 this.filter.setValue('');
134 removeItem(item: string) {
135 this.triggerSelection(
136 this.options.find((option: SelectBadgesOption) => option.name === item && option.selected)