This repository has been archived by the owner on Nov 18, 2022. It is now read-only.
forked from DSchrupert/ng-selectize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathng-selectize.component.ts
265 lines (233 loc) · 7.5 KB
/
ng-selectize.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import {
Input,
OnInit,
OnChanges,
SimpleChanges,
DoCheck,
forwardRef,
Component,
ViewChild,
Output,
EventEmitter
} from "@angular/core";
import {NG_VALUE_ACCESSOR, ControlValueAccessor, FormControl} from "@angular/forms";
declare const $:any;
const isEqual = require('lodash.isequal');
const cloneDeep = require('lodash.clonedeep');
const find = require('lodash.find');
const differenceWith = require('lodash.differencewith');
export const SELECTIZE_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NgSelectizeComponent),
multi: true
};
@Component({
selector: 'ng-selectize',
template: `<select #selectizeInput></select>`,
providers: [SELECTIZE_VALUE_ACCESSOR]
})
export class NgSelectizeComponent implements OnInit, OnChanges, DoCheck, ControlValueAccessor {
@Input('config') config: any;
@Input('options') options: any[];
@Input('optionGroups') optionGroups: any[];
@Input('placeholder') placeholder: string;
@Input('hasOptionsPlaceholder') hasOptionsPlaceholder: string;
@Input('noOptionsPlaceholder') noOptionsPlaceholder: string;
@Input('enabled') enabled: boolean = true;
@Input('ngModel') _value: string[];
@Input() formControl:FormControl;
@Input() errorClass:string;
@Output() onBlur:EventEmitter<void> = new EventEmitter<void>(false);
@ViewChild('selectizeInput') selectizeInput: any;
private selectize: any;
private _oldOptions: any[];
private _oldOptionGroups: any[];
// Control value accessors.
private onTouchedCallback: () => void = () => {};
private onChangeCallback: (_: any) => void = () => {};
constructor() {}
ngOnInit(): void {
this.reset();
}
reset() {
this.selectize = $(this.selectizeInput.nativeElement).selectize(this.config)[0].selectize;
this.selectize.on('change', this.onSelectizeValueChange.bind(this));
this.selectize.on('option_add', this.onSelectizeOptionAdd.bind(this));
this.selectize.on('blur', this.onBlurEvent.bind(this));
this.onSelectizeOptionsChange();
this.onSelectizeOptionGroupChange();
if (this.placeholder && this.placeholder.length > 0) {
this.updatePlaceholder();
}
this._oldOptions = cloneDeep(this.options);
this._oldOptionGroups = cloneDeep(this.optionGroups);
this.onEnabledStatusChange();
}
/**
* Change detection for primitive types.
*/
ngOnChanges(changes: SimpleChanges): void {
if (this.selectize) {
if (changes.hasOwnProperty('placeholder') || changes.hasOwnProperty('hasOptionsPlaceholder') || changes.hasOwnProperty('noOptionsPlaceholder')) {
this.updatePlaceholder();
}
if (changes.hasOwnProperty('enabled')) {
this.onEnabledStatusChange();
}
}
}
/**
* Implementing deep check for option comparison
*
* FIXME -> Implement deep check to only compare against label and value fields.
*/
ngDoCheck(): void {
if (!isEqual(this._oldOptions, this.options)) {
this.onSelectizeOptionsChange();
this._oldOptions = cloneDeep(this.options);
}
if (!isEqual(this._oldOptionGroups, this.optionGroups)) {
this.onSelectizeOptionGroupChange();
this._oldOptionGroups = cloneDeep(this.optionGroups);
}
this.evalHasError();
}
onBlurEvent() {
if (this.formControl) {
this.formControl.markAsTouched();
}
this.onBlur.emit();
this.evalHasError();
}
/**
* Refresh selected values when options change.
*/
onSelectizeOptionAdd(optionValue:string): void {
if (this.value) {
const items = typeof this.value === 'string' ? [this.value] : this.value;
if (find(items, (value:any) => {
return value === optionValue
})) {
this.selectize.addItem(optionValue, true);
}
}
}
evalHasError() {
if(this.formControl && this.formControl.touched && this.formControl.invalid) {
$(this.selectize.$control).parent().addClass(this.errorClass || 'has-error');
} else {
$(this.selectize.$control).parent().removeClass(this.errorClass || 'has-error');
}
}
/**
* Update the current placeholder based on the given input parameter.
*/
updatePlaceholder(): void {
this.selectize.settings.placeholder = this.getPlaceholder();
this.selectize.updatePlaceholder();
this.selectize.showInput(); // Without this, when options are cleared placeholder only appears after focus.
}
/**
* Called when a change is detected in the 'enabled' input field.
* Sets the selectize state based on the new value.
*/
onEnabledStatusChange(): void {
this.enabled ? this.selectize.enable() : this.selectize.disable();
}
/**
* Triggered when a change is detected with the given set of options.
*/
onSelectizeOptionsChange(): void {
const optionsRemoved = differenceWith(this._oldOptions, this.options, (oldValue:any, newValue:any) => {
return oldValue[this.selectize.settings.valueField] === newValue[this.selectize.settings.valueField]
&& oldValue[this.selectize.settings.labelField] === newValue[this.selectize.settings.labelField];
});
const newOptionsAdded = differenceWith(this.options, this._oldOptions, (oldValue:any, newValue:any) => {
return oldValue[this.selectize.settings.valueField] === newValue[this.selectize.settings.valueField]
&& oldValue[this.selectize.settings.labelField] === newValue[this.selectize.settings.labelField];
});
if (optionsRemoved && optionsRemoved.length > 0) {
optionsRemoved.forEach((option:any) => {
this.selectize.removeOption(option[this.selectize.settings.valueField]);
});
}
if (newOptionsAdded && newOptionsAdded.length > 0) {
newOptionsAdded.forEach((option:any) => {
this.selectize.addOption(cloneDeep(option));
});
}
this.updatePlaceholder();
}
/**
* Triggered when a change is detected with the given set of option groups.
*/
onSelectizeOptionGroupChange(): void {
if (this.optionGroups != null && this.optionGroups.length > 0) {
this.optionGroups.forEach((optionGroup) => {
this.selectize.addOptionGroup(optionGroup.id, optionGroup);
});
}
}
/**
* Dispatches change event when a value change is detected.
* @param $event
*/
onSelectizeValueChange($event:any): void {
this.value = this.selectize.getValue();
}
/**
* Returns the applicable placeholder.
*/
getPlaceholder(): string {
let newPlaceholder: string;
if (this.options != null && this.options.length > 0 && this.hasOptionsPlaceholder != null && this.hasOptionsPlaceholder.length > 0) {
newPlaceholder = this.hasOptionsPlaceholder;
} else if ((this.options == null || this.options.length == 0) && (this.noOptionsPlaceholder != null && this.noOptionsPlaceholder.length > 0)) { // no options
newPlaceholder = this.noOptionsPlaceholder
} else {
newPlaceholder = this.placeholder;
}
return newPlaceholder;
}
/**
* Implementation from ControlValueAccessor
*
* Empty check on 'obj' removed due to restriction on resetting the field.
* From testing, async should still function appropriately.
*
* FIXME This might not be necessary anymore..
*
* @param obj
*/
writeValue(obj: any): void {
if (obj !== this._value) {
this._value = obj;
}
this.selectize.setValue(this._value);
}
/**
* Implementation from ControlValueAccessor, callback for (ngModelChange)
* @param fn
*/
registerOnChange(fn: any): void {
this.onChangeCallback = fn;
}
/**
* Implementation from ControlValueAccessor
* @param fn
*/
registerOnTouched(fn: any): void {
this.onTouchedCallback = fn;
}
get value(): string[] {
return this._value;
}
set value(value: string[]) {
if (this._value !== value) {
setTimeout(() => { // Fix for change after check issue in development mode.
this._value = cloneDeep(value);
this.onChangeCallback(this._value);
});
}
}
}