forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
select_multiple_control_value_accessor.ts
300 lines (271 loc) · 8.27 KB
/
select_multiple_control_value_accessor.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, ElementRef, forwardRef, Host, Input, OnDestroy, Optional, Renderer2, StaticProvider} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
export const SELECT_MULTIPLE_VALUE_ACCESSOR: StaticProvider = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SelectMultipleControlValueAccessor),
multi: true
};
function _buildValueString(id: string, value: any): string {
if (id == null) return `${value}`;
if (typeof value === 'string') value = `'${value}'`;
if (value && typeof value === 'object') value = 'Object';
return `${id}: ${value}`.slice(0, 50);
}
function _extractId(valueString: string): string {
return valueString.split(':')[0];
}
/** Mock interface for HTML Options */
interface HTMLOption {
value: string;
selected: boolean;
}
/** Mock interface for HTMLCollection */
abstract class HTMLCollection {
// TODO(issue/24571): remove '!'.
length!: number;
abstract item(_: number): HTMLOption;
}
/**
* @description
* The `ControlValueAccessor` for writing multi-select control values and listening to multi-select
* control changes. The value accessor is used by the `FormControlDirective`, `FormControlName`, and
* `NgModel` directives.
*
* @see `SelectControlValueAccessor`
*
* @usageNotes
*
* ### Using a multi-select control
*
* The follow example shows you how to use a multi-select control with a reactive form.
*
* ```ts
* const countryControl = new FormControl();
* ```
*
* ```
* <select multiple name="countries" [formControl]="countryControl">
* <option *ngFor="let country of countries" [ngValue]="country">
* {{ country.name }}
* </option>
* </select>
* ```
*
* ### Customizing option selection
*
* To customize the default option comparison algorithm, `<select>` supports `compareWith` input.
* See the `SelectControlValueAccessor` for usage.
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector:
'select[multiple][formControlName],select[multiple][formControl],select[multiple][ngModel]',
host: {'(change)': 'onChange($event.target)', '(blur)': 'onTouched()'},
providers: [SELECT_MULTIPLE_VALUE_ACCESSOR]
})
export class SelectMultipleControlValueAccessor implements ControlValueAccessor {
/**
* @description
* The current value
*/
value: any;
/** @internal */
_optionMap: Map<string, ɵNgSelectMultipleOption> = new Map<string, ɵNgSelectMultipleOption>();
/** @internal */
_idCounter: number = 0;
/**
* @description
* The registered callback function called when a change event occurs on the input element.
*/
onChange = (_: any) => {};
/**
* @description
* The registered callback function called when a blur event occurs on the input element.
*/
onTouched = () => {};
/**
* @description
* Tracks the option comparison algorithm for tracking identities when
* checking for changes.
*/
@Input()
set compareWith(fn: (o1: any, o2: any) => boolean) {
if (typeof fn !== 'function') {
throw new Error(`compareWith must be a function, but received ${JSON.stringify(fn)}`);
}
this._compareWith = fn;
}
private _compareWith: (o1: any, o2: any) => boolean = Object.is;
constructor(private _renderer: Renderer2, private _elementRef: ElementRef) {}
/**
* @description
* Sets the "value" property on one or of more
* of the select's options.
*
* @param value The value
*/
writeValue(value: any): void {
this.value = value;
let optionSelectedStateSetter: (opt: ɵNgSelectMultipleOption, o: any) => void;
if (Array.isArray(value)) {
// convert values to ids
const ids = value.map((v) => this._getOptionId(v));
optionSelectedStateSetter = (opt, o) => {
opt._setSelected(ids.indexOf(o.toString()) > -1);
};
} else {
optionSelectedStateSetter = (opt, o) => {
opt._setSelected(false);
};
}
this._optionMap.forEach(optionSelectedStateSetter);
}
/**
* @description
* Registers a function called when the control value changes
* and writes an array of the selected options.
*
* @param fn The callback function
*/
registerOnChange(fn: (value: any) => any): void {
this.onChange = (_: any) => {
const selected: Array<any> = [];
if (_.hasOwnProperty('selectedOptions')) {
const options: HTMLCollection = _.selectedOptions;
for (let i = 0; i < options.length; i++) {
const opt: any = options.item(i);
const val: any = this._getOptionValue(opt.value);
selected.push(val);
}
}
// Degrade on IE
else {
const options: HTMLCollection = <HTMLCollection>_.options;
for (let i = 0; i < options.length; i++) {
const opt: HTMLOption = options.item(i);
if (opt.selected) {
const val: any = this._getOptionValue(opt.value);
selected.push(val);
}
}
}
this.value = selected;
fn(selected);
};
}
/**
* @description
* Registers a function called when the control is touched.
*
* @param fn The callback function
*/
registerOnTouched(fn: () => any): void {
this.onTouched = fn;
}
/**
* Sets the "disabled" property on the select input element.
*
* @param isDisabled The disabled value
*/
setDisabledState(isDisabled: boolean): void {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
}
/** @internal */
_registerOption(value: ɵNgSelectMultipleOption): string {
const id: string = (this._idCounter++).toString();
this._optionMap.set(id, value);
return id;
}
/** @internal */
_getOptionId(value: any): string|null {
for (const id of Array.from(this._optionMap.keys())) {
if (this._compareWith(this._optionMap.get(id)!._value, value)) return id;
}
return null;
}
/** @internal */
_getOptionValue(valueString: string): any {
const id: string = _extractId(valueString);
return this._optionMap.has(id) ? this._optionMap.get(id)!._value : valueString;
}
}
/**
* @description
* Marks `<option>` as dynamic, so Angular can be notified when options change.
*
* @see `SelectMultipleControlValueAccessor`
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({selector: 'option'})
export class ɵNgSelectMultipleOption implements OnDestroy {
// TODO(issue/24571): remove '!'.
id!: string;
/** @internal */
_value: any;
constructor(
private _element: ElementRef, private _renderer: Renderer2,
@Optional() @Host() private _select: SelectMultipleControlValueAccessor) {
if (this._select) {
this.id = this._select._registerOption(this);
}
}
/**
* @description
* Tracks the value bound to the option element. Unlike the value binding,
* ngValue supports binding to objects.
*/
@Input('ngValue')
set ngValue(value: any) {
if (this._select == null) return;
this._value = value;
this._setElementValue(_buildValueString(this.id, value));
this._select.writeValue(this._select.value);
}
/**
* @description
* Tracks simple string values bound to the option element.
* For objects, use the `ngValue` input binding.
*/
@Input('value')
set value(value: any) {
if (this._select) {
this._value = value;
this._setElementValue(_buildValueString(this.id, value));
this._select.writeValue(this._select.value);
} else {
this._setElementValue(value);
}
}
/** @internal */
_setElementValue(value: string): void {
this._renderer.setProperty(this._element.nativeElement, 'value', value);
}
/** @internal */
_setSelected(selected: boolean) {
this._renderer.setProperty(this._element.nativeElement, 'selected', selected);
}
/**
* @description
* Lifecycle method called before the directive's instance is destroyed. For internal use only.
*/
ngOnDestroy(): void {
if (this._select) {
this._select._optionMap.delete(this.id);
this._select.writeValue(this._select.value);
}
}
}
export {ɵNgSelectMultipleOption as NgSelectMultipleOption};