• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IgniteUI / igniteui-angular / 9345918668

03 Jun 2024 07:18AM UTC coverage: 92.216%. Remained the same
9345918668

push

github

web-flow
Merge pull request #14247 from IgniteUI/ikitanov/fix-14053-16.1.x

fix(simple-combo): Update the model value only if selection is changed

15438 of 18156 branches covered (85.03%)

27010 of 29290 relevant lines covered (92.22%)

29512.59 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.29
/projects/igniteui-angular/src/lib/simple-combo/simple-combo.component.ts
1
import { NgIf, NgTemplateOutlet } from '@angular/common';
2
import {
3
    AfterViewInit, ChangeDetectorRef, Component, DoCheck, ElementRef, EventEmitter, HostListener, Inject, Injector,
4
    Optional, Output, ViewChild
5
} from '@angular/core';
6
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
7
import { takeUntil } from 'rxjs/operators';
8

9
import { IgxComboAddItemComponent } from '../combo/combo-add-item.component';
10
import { IgxComboDropDownComponent } from '../combo/combo-dropdown.component';
11
import { IgxComboItemComponent } from '../combo/combo-item.component';
12
import { IgxComboAPIService } from '../combo/combo.api';
13
import { IgxComboBaseDirective, IGX_COMBO_COMPONENT } from '../combo/combo.common';
14
import { DisplayDensityToken, IDisplayDensityOptions } from '../core/density';
15
import { IgxSelectionAPIService } from '../core/selection';
16
import { CancelableEventArgs, IBaseCancelableBrowserEventArgs, IBaseEventArgs, PlatformUtil } from '../core/utils';
17
import { IgxButtonDirective } from '../directives/button/button.directive';
18
import { IgxForOfDirective } from '../directives/for-of/for_of.directive';
19
import { IgxRippleDirective } from '../directives/ripple/ripple.directive';
20
import { IgxTextSelectionDirective } from '../directives/text-selection/text-selection.directive';
21
import { IgxIconService } from '../icon/icon.service';
22
import { IgxInputGroupType, IGX_INPUT_GROUP_TYPE } from '../input-group/public_api';
23
import { IgxComboFilteringPipe, IgxComboGroupingPipe } from '../combo/combo.pipes';
24
import { IgxDropDownItemNavigationDirective } from '../drop-down/drop-down-navigation.directive';
25
import { IgxIconComponent } from '../icon/icon.component';
26
import { IgxSuffixDirective } from '../directives/suffix/suffix.directive';
27
import { IgxInputDirective } from '../directives/input/input.directive';
28
import { IgxInputGroupComponent } from '../input-group/input-group.component';
29

30
/** Emitted when an igx-simple-combo's selection is changing.  */
31
export interface ISimpleComboSelectionChangingEventArgs extends CancelableEventArgs, IBaseEventArgs {
32
    /** An object which represents the value that is currently selected */
33
    oldSelection: any;
34
    /** An object which represents the value that will be selected after this event */
35
    newSelection: any;
36
    /** The text that will be displayed in the combo text box */
37
    displayText: string;
38
}
39

40
/**
41
 * Represents a drop-down list that provides filtering functionality, allowing users to choose a single option from a predefined list.
42
 *
43
 * @igxModule IgxSimpleComboModule
44
 * @igxTheme igx-combo-theme
45
 * @igxKeywords combobox, single combo selection
46
 * @igxGroup Grids & Lists
47
 *
2✔
48
 * @remarks
49
 * It provides the ability to filter items as well as perform single selection on the provided data.
50
 * Additionally, it exposes keyboard navigation and custom styling capabilities.
1,084✔
51
 * @example
52
 * ```html
53
 * <igx-simple-combo [itemsMaxHeight]="250" [data]="locationData"
54
 *  [displayKey]="'field'" [valueKey]="'field'"
5,182!
55
 *  placeholder="Location" searchPlaceholder="Search...">
198✔
56
 * </igx-simple-combo>
57
 * ```
58
 */
59
@Component({
9,646✔
60
    selector: 'igx-simple-combo',
61
    templateUrl: 'simple-combo.component.html',
62
    providers: [
207✔
63
        IgxComboAPIService,
64
        { provide: IGX_COMBO_COMPONENT, useExisting: IgxSimpleComboComponent },
65
        { provide: NG_VALUE_ACCESSOR, useExisting: IgxSimpleComboComponent, multi: true }
89✔
66
    ],
67
    standalone: true,
68
    imports: [IgxInputGroupComponent, IgxInputDirective, IgxTextSelectionDirective, NgIf, IgxSuffixDirective, NgTemplateOutlet, IgxIconComponent, IgxComboDropDownComponent, IgxDropDownItemNavigationDirective, IgxForOfDirective, IgxComboItemComponent, IgxComboAddItemComponent, IgxButtonDirective, IgxRippleDirective, IgxComboFilteringPipe, IgxComboGroupingPipe]
90✔
69
})
90✔
70
export class IgxSimpleComboComponent extends IgxComboBaseDirective implements ControlValueAccessor, AfterViewInit, DoCheck {
90✔
71
    /** @hidden @internal */
72
    @ViewChild(IgxComboDropDownComponent, { static: true })
90✔
73
    public dropdown: IgxComboDropDownComponent;
90✔
74

90✔
75
    /** @hidden @internal */
90✔
76
    @ViewChild(IgxComboAddItemComponent)
1,535✔
77
    public addItem: IgxComboAddItemComponent;
1,535✔
78

79
    /**
15✔
80
     * Emitted when item selection is changing, before the selection completes
81
     *
1,520✔
82
     * ```html
1,520✔
83
     * <igx-simple-combo (selectionChanging)='handleSelection()'></igx-simple-combo>
84
     * ```
90✔
85
     */
86
    @Output()
87
    public selectionChanging = new EventEmitter<ISimpleComboSelectionChangingEventArgs>();
5✔
88

2✔
89
    @ViewChild(IgxTextSelectionDirective, { static: true })
2✔
90
    private textSelection: IgxTextSelectionDirective;
2✔
91

92
    /** @hidden @internal */
93
    public composing = false;
3✔
94

2✔
95
    private _updateInput = true;
2✔
96

97
    private _collapsing = false;
1!
98

1✔
99
    /** @hidden @internal */
100
    public get filteredData(): any[] | null {
101
        return this._filteredData;
102
    }
103
    /** @hidden @internal */
104
    public set filteredData(val: any[] | null) {
105
        this._filteredData = this.groupKey ? (val || []).filter((e) => e.isHeader !== true) : val;
106
        this.checkMatch();
107
    }
108

109
    /** @hidden @internal */
110
    public override get searchValue(): string {
111
        return this._searchValue;
59!
112
    }
59✔
113
    public override set searchValue(val: string) {
59✔
114
        this._searchValue = val;
115
    }
116

117
    private get selectedItem(): any {
118
        return this.selectionService.get(this.id).values().next().value;
119
    }
120

121
    constructor(elementRef: ElementRef,
122
        cdr: ChangeDetectorRef,
123
        selectionService: IgxSelectionAPIService,
124
        comboAPI: IgxComboAPIService,
125
        _iconService: IgxIconService,
4✔
126
        private platformUtil: PlatformUtil,
127
        @Optional() @Inject(DisplayDensityToken) _displayDensityOptions: IDisplayDensityOptions,
128
        @Optional() @Inject(IGX_INPUT_GROUP_TYPE) _inputGroupType: IgxInputGroupType,
129
        @Optional() _injector: Injector) {
56✔
130
        super(elementRef, cdr, selectionService, comboAPI,
55✔
131
            _iconService, _displayDensityOptions, _inputGroupType, _injector);
55✔
132
        this.comboAPI.register(this);
55✔
133
    }
55✔
134

55✔
135
    /** @hidden @internal */
136
    @HostListener('keydown.ArrowDown', ['$event'])
137
    @HostListener('keydown.Alt.ArrowDown', ['$event'])
138
    public onArrowDown(event: Event): void {
75✔
139
        if (this.collapsed) {
2✔
140
            event.preventDefault();
1✔
141
            event.stopPropagation();
10!
142
            this.open();
10!
143
        } else {
×
144
            if (this.virtDir.igxForOf.length > 0 && !this.selectedItem) {
145
                this.dropdown.navigateNext();
10✔
146
                this.dropdownContainer.nativeElement.focus();
147
            } else if (this.allowCustomValues) {
1!
148
                this.addItem?.element.nativeElement.focus();
149
            }
150
        }
151
    }
×
152

153
    /**
154
     * Select a defined item
155
     *
75✔
156
     * @param item the item to be selected
65!
157
     * ```typescript
×
158
     * this.combo.select("New York");
159
     * ```
65✔
160
     */
65✔
161
    public select(item: any): void {
65✔
162
        if (item !== undefined) {
38✔
163
            const newSelection = this.selectionService.add_items(this.id, item instanceof Array ? item : [item], true);
38✔
164
            this.setSelection(newSelection);
165
        }
27✔
166
    }
167

75✔
168
    /**
18✔
169
     * Deselect the currently selected item
4✔
170
     *
171
     * @param item the items to be deselected
172
     * ```typescript
75✔
173
     * this.combo.deselect("New York");
29!
174
     * ```
×
175
     */
176
    public deselect(): void {
29✔
177
        this.clearSelection();
28✔
178
    }
179

180
    /** @hidden @internal */
1✔
181
    public writeValue(value: any): void {
1✔
182
        const oldSelection = this.selection;
183
        this.selectionService.select_items(this.id, this.isValid(value) ? [value] : [], true);
29✔
184
        this.cdr.markForCheck();
185
        this._displayValue = this.createDisplayText(super.selection, oldSelection);
186
        this._value = this.valueKey ? super.selection.map(item => item[this.valueKey]) : super.selection;
187
        this.filterValue = this._displayValue?.toString() || '';
75✔
188
    }
68✔
189

68✔
190
    /** @hidden @internal */
191
    public override ngAfterViewInit(): void {
75✔
192
        this.virtDir.contentSizeChange.pipe(takeUntil(this.destroy$)).subscribe(() => {
193
            if (this.selection.length > 0) {
194
                const index = this.virtDir.igxForOf.findIndex(e => {
195
                    let current = e? e[this.valueKey] : undefined;
286✔
196
                    if (this.valueKey === null || this.valueKey === undefined) {
10✔
197
                        current = e;
10✔
198
                    }
199
                    return current === this.selection[0];
286✔
200
                });
201
                if (!this.isRemote) {
202
                    // navigate to item only if we have local data
203
                    // as with remote data this will fiddle with igxFor's scroll handler
39✔
204
                    // and will trigger another chunk load which will break the visualization
37✔
205
                    this.dropdown.navigateItem(index);
206
                }
39✔
207
            }
8✔
208
        });
209
        this.dropdown.opening.pipe(takeUntil(this.destroy$)).subscribe((args) => {
39✔
210
            if (args.cancel) {
211
                return;
1✔
212
            }
1✔
213
            this._collapsing = false;
1✔
214
            const filtered = this.filteredData.find(this.findAllMatches);
215
            if (filtered === undefined || filtered === null) {
39✔
216
                this.filterValue = this.searchValue = this.comboInput.value;
2✔
217
                return;
218
            }
219
            this.filterValue = this.searchValue = '';
39✔
220
        });
20✔
221
        this.dropdown.opened.pipe(takeUntil(this.destroy$)).subscribe(() => {
222
            if (this.composing) {
39✔
223
                this.comboInput.focus();
39✔
224
            }
225
        });
226
        this.dropdown.closing.pipe(takeUntil(this.destroy$)).subscribe((args) => {
227
            if (args.cancel) {
3✔
228
                return;
1✔
229
            }
1✔
230
            if (this.getEditElement() && !args.event) {
231
                this._collapsing = true;
232
            } else {
233
                this.clearOnBlur();
234
                this._onTouchedCallback();
53✔
235
            }
5✔
236
            this.comboInput.focus();
5!
237
        });
×
238

239
        // in reactive form the control is not present initially
5✔
240
        // and sets the selection to an invalid value in writeValue method
5✔
241
        if (!this.isValid(this.selectedItem)) {
5✔
242
            this.selectionService.clear(this.id);
5✔
243
            this._displayValue = '';
244
        }
5✔
245

5✔
246
        super.ngAfterViewInit();
247
    }
48✔
248

249
    /** @hidden @internal */
2✔
250
    public override ngDoCheck(): void {
2✔
251
        if (this.data?.length && this.selection.length && !this._displayValue) {
252
            this._displayValue = this.createDisplayText(this.selection, []);
48✔
253
            this._value = this.valueKey ? this.selection.map(item => item[this.valueKey]) : this.selection;
10✔
254
        }
10✔
255
        super.ngDoCheck();
256
    }
48✔
257

48✔
258
    /** @hidden @internal */
259
    public override handleInputChange(event?: any): void {
260
        if (event !== undefined) {
261
            this.filterValue = this.searchValue = typeof event === 'string' ? event : event.target.value;
32✔
262
        }
1✔
263
        if (this.collapsed && this.comboInput.focused) {
1!
264
            this.open();
×
265
        }
266
        if (!this.comboInput.value.trim() && this.selection.length) {
1✔
267
            // handle clearing of input by space
268
            this.clearSelection();
269
            this._onChangeCallback(null);
270
            this.filterValue = '';
271
        }
4!
272
        if (this.selection.length) {
×
273
            this.selectionService.clear(this.id);
×
274
        }
×
275
        // when filtering the focused item should be the first item or the currently selected item
276
        if (!this.dropdown.focusedItem || this.dropdown.focusedItem.id !== this.dropdown.items[0].id) {
4!
277
            this.dropdown.navigateFirst();
×
278
        }
279
        super.handleInputChange(event);
280
        this.composing = true;
281
    }
282

26✔
283
    /** @hidden @internal */
26✔
284
    public handleInputClick(): void {
285
        if (this.collapsed) {
286
            this.open();
287
            this.comboInput.focus();
288
        }
289
    }
15✔
290

12✔
291
    /** @hidden @internal */
292
    public override handleKeyDown(event: KeyboardEvent): void {
15✔
293
        if (event.key === this.platformUtil.KEYMAP.ENTER) {
294
            const filtered = this.filteredData.find(this.findAllMatches);
295
            if (filtered === null || filtered === undefined) {
296
                return;
29✔
297
            }
298
            this.select(this.dropdown.focusedItem.itemID);
299
            event.preventDefault();
300
            event.stopPropagation();
6✔
301
            this.close();
1✔
302
            // manually trigger text selection as it will not be triggered during editing
303
            this.textSelection.trigger();
5✔
304
            return;
5✔
305
        }
2✔
306
        if (event.key === this.platformUtil.KEYMAP.BACKSPACE
307
            || event.key === this.platformUtil.KEYMAP.DELETE) {
5✔
308
            this._updateInput = false;
5✔
309
            this.clearSelection(true);
5✔
310
        }
5✔
311
        if (!this.collapsed && event.key === this.platformUtil.KEYMAP.TAB) {
5✔
312
            this.clearOnBlur();
313
            this.close();
314
        }
315
        this.composing = false;
18✔
316
        super.handleKeyDown(event);
18✔
317
    }
15✔
318

319
    /** @hidden @internal */
18✔
320
    public handleKeyUp(event: KeyboardEvent): void {
321
        if (event.key === this.platformUtil.KEYMAP.ARROW_DOWN) {
322
            const firstItem = this.selectionService.first_item(this.id);
323
            this.dropdown.focusedItem = firstItem && this.filteredData.length > 0
31✔
324
                ? this.dropdown.items.find(i => i.itemID === firstItem)
31✔
325
                : this.dropdown.items[0];
31✔
326
            this.dropdownContainer.nativeElement.focus();
31✔
327
        }
1✔
328
    }
329

30✔
330
    /** @hidden @internal */
331
    public handleItemKeyDown(event: KeyboardEvent): void {
30✔
332
        if (event.key === this.platformUtil.KEYMAP.ARROW_UP && event.altKey) {
30✔
333
            this.close();
334
            this.comboInput.focus();
335
            return;
336
        }
6✔
337
        if (event.key === this.platformUtil.KEYMAP.ENTER) {
2✔
338
            this.comboInput.focus();
339
        }
340
    }
4✔
341

342
    /** @hidden @internal */
343
    public handleItemClick(): void {
344
        this.close();
345
        this.comboInput.focus();
5✔
346
    }
5✔
347

3✔
348
    /** @hidden @internal */
349
    public override onBlur(): void {
350
        // when clicking the toggle button to close the combo and immediately clicking outside of it
351
        // the collapsed state is not modified as the dropdown is still not closed
87✔
352
        if (this.collapsed || this._collapsing) {
87!
353
            this.clearOnBlur();
87✔
354
        }
87✔
355
        super.onBlur();
356
    }
357

358
    /** @hidden @internal */
359
    public getEditElement(): HTMLElement {
360
        return this.comboInput.nativeElement;
361
    }
87✔
362

70✔
363
    /** @hidden @internal */
364
    public handleClear(event: Event): void {
365
        if (this.disabled) {
87✔
366
            return;
86✔
367
        }
368
        this.clearSelection(true);
369
        if(!this.collapsed){
86✔
370
            this.focusSearchInput(true);
86✔
371
        }
86✔
372
        event.stopPropagation();
86✔
373

84!
374
        this.comboInput.value = this.filterValue = this.searchValue = '';
375
        this.dropdown.focusedItem = null;
376
        this.composing = false;
377
        this.comboInput.focus();
86✔
378
    }
86✔
379

380
    /** @hidden @internal */
1!
381
    public handleOpened(): void {
1✔
382
        this.triggerCheck();
383
        if (!this.comboInput.focused) {
384
            this.dropdownContainer.nativeElement.focus();
385
        }
236✔
386
        this.opened.emit({ owner: this });
31!
387
    }
31✔
388

389
    /** @hidden @internal */
205✔
390
    public override handleClosing(e: IBaseCancelableBrowserEventArgs): void {
391
        const args: IBaseCancelableBrowserEventArgs = { owner: this, event: e.event, cancel: e.cancel };
392
        this.closing.emit(args);
79✔
393
        e.cancel = args.cancel;
394
        if (e.cancel) {
126✔
395
            return;
396
        }
397

31✔
398
        this.composing = false;
10✔
399
        // explicitly update selection and trigger text selection so that we don't have to force CD
10✔
400
        this.textSelection.selected = true;
401
        this.textSelection.trigger();
21✔
402
    }
21✔
403

21!
404
    /** @hidden @internal */
405
    public focusSearchInput(opening?: boolean): void {
406
        if (opening) {
21✔
407
            this.dropdownContainer.nativeElement.focus();
53✔
408
        } else {
53✔
409
            this.comboInput.nativeElement.focus();
21✔
410
        }
411
    }
412

32✔
413
    /** @hidden @internal */
414
    public override onClick(event: Event): void {
415
        super.onClick(event);
416
        if (this.comboInput.value.length === 0) {
28✔
417
            this.virtDir.scrollTo(0);
28✔
418
        }
1✔
419
    }
420

28✔
421
    protected findAllMatches = (element: any): boolean => {
422
        const value = this.displayKey ? element[this.displayKey] : element;
423
        if (value === null || value === undefined || value === '') {
23✔
424
            // we can accept null, undefined and empty strings as empty display values
2!
425
            return true;
2✔
426
        }
2✔
427
        const searchValue = this.searchValue || this.comboInput.value;
1✔
428
        return !!searchValue && value.toString().toLowerCase().includes(searchValue.toLowerCase());
429
    };
2✔
430

431
    protected setSelection(newSelection: any): void {
21✔
432
        const newSelectionAsArray = newSelection ? Array.from(newSelection) as IgxComboItemComponent[] : [];
433
        const oldSelectionAsArray = Array.from(this.selectionService.get(this.id) || []);
21✔
434
        const displayText = this.createDisplayText(this.convertKeysToItems(newSelectionAsArray), oldSelectionAsArray);
15✔
435
        const args: ISimpleComboSelectionChangingEventArgs = {
436
            newSelection: newSelectionAsArray[0],
437
            oldSelection: oldSelectionAsArray[0],
438
            displayText,
×
439
            owner: this,
×
440
            cancel: false
441
        };
442
        if (args.newSelection !== args.oldSelection) {
16✔
443
            this.selectionChanging.emit(args);
16✔
444
        }
445
        // TODO: refactor below code as it sets the selection and the display text
446
        if (!args.cancel) {
216✔
447
            let argsSelection = this.isValid(args.newSelection)
122✔
448
                ? args.newSelection
449
                : [];
450
            argsSelection = Array.isArray(argsSelection) ? argsSelection : [argsSelection];
2✔
451
            this.selectionService.select_items(this.id, argsSelection, true);
452
            this._value = argsSelection;
453
            if (this._updateInput) {
454
                this.comboInput.value = this._displayValue = this.searchValue = displayText !== args.displayText
455
                    ? args.displayText
456
                    : this.createDisplayText(this.selection, [args.oldSelection]);
457
            }
458
            this._onChangeCallback(args.newSelection);
459
            this._updateInput = true;
460
        } else if (this.isRemote) {
461
            this.registerRemoteEntries(newSelectionAsArray, false);
2✔
462
        }
463
    }
464

465
    protected createDisplayText(newSelection: any[], oldSelection: any[]): string {
466
        if (this.isRemote) {
467
            const selection = this.valueKey ? newSelection.map(item => item[this.valueKey]) : newSelection;
468
            return this.getRemoteSelection(selection, oldSelection);
469
        }
2✔
470

471
        if (this.displayKey !== null
472
            && this.displayKey !== undefined
473
            && newSelection.length > 0) {
474
            return newSelection.filter(e => e).map(e => e[this.displayKey])[0]?.toString() || '';
475
        }
476

477
        return newSelection[0]?.toString() || '';
478
    }
479

480
    protected override getRemoteSelection(newSelection: any[], oldSelection: any[]): string {
481
        if (!newSelection.length) {
482
            this.registerRemoteEntries(oldSelection, false);
483
            return '';
484
        }
485

486
        this.registerRemoteEntries(oldSelection, false);
487
        this.registerRemoteEntries(newSelection);
488
        return Object.keys(this._remoteSelection).map(e => this._remoteSelection[e])[0] || '';
489
    }
490

491
    /** Contains key-value pairs of the selected valueKeys and their resp. displayKeys */
492
    protected override registerRemoteEntries(ids: any[], add = true) {
493
        const selection = this.getValueDisplayPairs(ids)[0];
494

495
        if (add && selection) {
496
            this._remoteSelection[selection[this.valueKey]] = selection[this.displayKey].toString();
497
        } else {
498
            this._remoteSelection = {};
499
        }
500
    }
501

502
    private clearSelection(ignoreFilter?: boolean): void {
503
        let newSelection = this.selectionService.get_empty();
504
        if (this.filteredData.length !== this.data.length && !ignoreFilter) {
505
            newSelection = this.selectionService.delete_items(this.id, this.selectionService.get_all_ids(this.filteredData, this.valueKey));
506
        }
507
        this.setSelection(newSelection);
508
    }
509

510
    private clearOnBlur(): void {
511
        if (this.isRemote) {
512
            const searchValue = this.searchValue || this.comboInput.value;
513
            const remoteValue = Object.keys(this._remoteSelection).map(e => this._remoteSelection[e])[0] || '';
514
            if (searchValue !== remoteValue) {
515
                this.clear();
516
            }
517
            return;
518
        }
519

520
        const filtered = this.filteredData.find(this.findMatch);
521
        // selecting null in primitive data returns undefined as the search text is '', but the item is null
522
        if (filtered === undefined && this.selectedItem !== null || !this.selection.length) {
523
            this.clear();
524
        }
525
    }
526

527
    private getElementVal(element: any): string {
528
        const elementVal = this.displayKey ? element[this.displayKey] : element;
529
        return String(elementVal);
530
    }
531

532
    private clear(): void {
533
        this.clearSelection(true);
534
        this.comboInput.value = this._displayValue = this.searchValue = '';
535
    }
536

537
    private isValid(value: any): boolean {
538
        return this.required
539
        ? value !== null && value !== '' && value !== undefined
540
        : value !== undefined;
541
    }
542
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc