primeng
Version:
[](https://badge.fury.io/js/primeng) [](https://www.npmjs.com/package/primeng) [ • 317 kB
JavaScript
import { CommonModule } from '@angular/common';
import { booleanAttribute, ChangeDetectionStrategy, Component, computed, ContentChild, ContentChildren, effect, EventEmitter, forwardRef, Input, NgModule, numberAttribute, Output, signal, ViewChild, ViewEncapsulation } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { Footer, Header, PrimeTemplate, SharedModule, TranslationKeys } from 'primeng/api';
import { DomHandler } from 'primeng/dom';
import { OverlayModule } from 'primeng/overlay';
import { RippleModule } from 'primeng/ripple';
import { ScrollerModule } from 'primeng/scroller';
import { TooltipModule } from 'primeng/tooltip';
import { ObjectUtils, UniqueComponentId } from 'primeng/utils';
import { CheckIcon } from 'primeng/icons/check';
import { SearchIcon } from 'primeng/icons/search';
import { TimesCircleIcon } from 'primeng/icons/timescircle';
import { TimesIcon } from 'primeng/icons/times';
import { ChevronDownIcon } from 'primeng/icons/chevrondown';
import { AutoFocusModule } from 'primeng/autofocus';
import { MinusIcon } from 'primeng/icons/minus';
import * as i0 from "@angular/core";
import * as i1 from "primeng/api";
import * as i2 from "@angular/common";
import * as i3 from "primeng/ripple";
import * as i4 from "primeng/overlay";
import * as i5 from "primeng/tooltip";
import * as i6 from "primeng/scroller";
import * as i7 from "primeng/autofocus";
export const MULTISELECT_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MultiSelect),
multi: true
};
export class MultiSelectItem {
config;
id;
option;
selected;
label;
disabled;
itemSize;
focused;
ariaPosInset;
ariaSetSize;
template;
checkIconTemplate;
itemCheckboxIconTemplate;
onClick = new EventEmitter();
onMouseEnter = new EventEmitter();
constructor(config) {
this.config = config;
}
onOptionClick(event) {
this.onClick.emit({
originalEvent: event,
option: this.option,
selected: this.selected
});
event.stopPropagation();
}
onOptionMouseEnter(event) {
this.onMouseEnter.emit({
originalEvent: event,
option: this.option,
selected: this.selected
});
}
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.0.1", ngImport: i0, type: MultiSelectItem, deps: [{ token: i1.PrimeNGConfig }], target: i0.ɵɵFactoryTarget.Component });
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "16.1.0", version: "18.0.1", type: MultiSelectItem, selector: "p-multiSelectItem", inputs: { id: "id", option: "option", selected: ["selected", "selected", booleanAttribute], label: "label", disabled: ["disabled", "disabled", booleanAttribute], itemSize: ["itemSize", "itemSize", numberAttribute], focused: ["focused", "focused", booleanAttribute], ariaPosInset: "ariaPosInset", ariaSetSize: "ariaSetSize", template: "template", checkIconTemplate: "checkIconTemplate", itemCheckboxIconTemplate: "itemCheckboxIconTemplate" }, outputs: { onClick: "onClick", onMouseEnter: "onMouseEnter" }, host: { classAttribute: "p-element" }, ngImport: i0, template: `
<li
pRipple
role="option"
[ngStyle]="{ height: itemSize + 'px' }"
class="p-multiselect-item"
[ngClass]="{ 'p-multiselect-item': true, 'p-disabled': disabled, 'p-focus': focused }"
[id]="id"
[attr.aria-label]="label"
[attr.aria-setsize]="ariaSetSize"
[attr.aria-posinset]="ariaPosInset"
[attr.aria-selected]="selected"
[attr.data-p-focused]="focused"
[attr.data-p-highlight]="selected"
[attr.data-p-disabled]="disabled"
[attr.aria-checked]="selected"
(click)="onOptionClick($event)"
(mouseenter)="onOptionMouseEnter($event)"
>
<div class="p-checkbox p-component" [ngClass]="{ 'p-variant-filled': config.inputStyle() === 'filled' }">
<div class="p-checkbox-box" [ngClass]="{ 'p-highlight': selected }">
<ng-container *ngIf="selected">
<CheckIcon *ngIf="!checkIconTemplate || !itemCheckboxIconTemplate" [styleClass]="'p-checkbox-icon'" [attr.aria-hidden]="true" />
<span *ngIf="checkIconTemplate" class="p-checkbox-icon" [attr.aria-hidden]="true">
<ng-template *ngTemplateOutlet="checkIconTemplate && !itemCheckboxIconTemplate"></ng-template>
<ng-template *ngTemplateOutlet="itemCheckboxIconTemplate; context: { $implicit: selected }"></ng-template>
</span>
</ng-container>
</div>
</div>
<span *ngIf="!template">{{ label ?? 'empty' }}</span>
<ng-container *ngTemplateOutlet="template; context: { $implicit: option }"></ng-container>
</li>
`, isInline: true, dependencies: [{ kind: "directive", type: i0.forwardRef(() => i2.NgClass), selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i0.forwardRef(() => i2.NgIf), selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i0.forwardRef(() => i2.NgTemplateOutlet), selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "directive", type: i0.forwardRef(() => i2.NgStyle), selector: "[ngStyle]", inputs: ["ngStyle"] }, { kind: "directive", type: i0.forwardRef(() => i3.Ripple), selector: "[pRipple]" }, { kind: "component", type: i0.forwardRef(() => CheckIcon), selector: "CheckIcon" }], encapsulation: i0.ViewEncapsulation.None });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.0.1", ngImport: i0, type: MultiSelectItem, decorators: [{
type: Component,
args: [{
selector: 'p-multiSelectItem',
template: `
<li
pRipple
role="option"
[ngStyle]="{ height: itemSize + 'px' }"
class="p-multiselect-item"
[ngClass]="{ 'p-multiselect-item': true, 'p-disabled': disabled, 'p-focus': focused }"
[id]="id"
[attr.aria-label]="label"
[attr.aria-setsize]="ariaSetSize"
[attr.aria-posinset]="ariaPosInset"
[attr.aria-selected]="selected"
[attr.data-p-focused]="focused"
[attr.data-p-highlight]="selected"
[attr.data-p-disabled]="disabled"
[attr.aria-checked]="selected"
(click)="onOptionClick($event)"
(mouseenter)="onOptionMouseEnter($event)"
>
<div class="p-checkbox p-component" [ngClass]="{ 'p-variant-filled': config.inputStyle() === 'filled' }">
<div class="p-checkbox-box" [ngClass]="{ 'p-highlight': selected }">
<ng-container *ngIf="selected">
<CheckIcon *ngIf="!checkIconTemplate || !itemCheckboxIconTemplate" [styleClass]="'p-checkbox-icon'" [attr.aria-hidden]="true" />
<span *ngIf="checkIconTemplate" class="p-checkbox-icon" [attr.aria-hidden]="true">
<ng-template *ngTemplateOutlet="checkIconTemplate && !itemCheckboxIconTemplate"></ng-template>
<ng-template *ngTemplateOutlet="itemCheckboxIconTemplate; context: { $implicit: selected }"></ng-template>
</span>
</ng-container>
</div>
</div>
<span *ngIf="!template">{{ label ?? 'empty' }}</span>
<ng-container *ngTemplateOutlet="template; context: { $implicit: option }"></ng-container>
</li>
`,
encapsulation: ViewEncapsulation.None,
host: {
class: 'p-element'
}
}]
}], ctorParameters: () => [{ type: i1.PrimeNGConfig }], propDecorators: { id: [{
type: Input
}], option: [{
type: Input
}], selected: [{
type: Input,
args: [{ transform: booleanAttribute }]
}], label: [{
type: Input
}], disabled: [{
type: Input,
args: [{ transform: booleanAttribute }]
}], itemSize: [{
type: Input,
args: [{ transform: numberAttribute }]
}], focused: [{
type: Input,
args: [{ transform: booleanAttribute }]
}], ariaPosInset: [{
type: Input
}], ariaSetSize: [{
type: Input
}], template: [{
type: Input
}], checkIconTemplate: [{
type: Input
}], itemCheckboxIconTemplate: [{
type: Input
}], onClick: [{
type: Output
}], onMouseEnter: [{
type: Output
}] } });
/**
* MultiSelect is used to select multiple items from a collection.
* @group Components
*/
export class MultiSelect {
el;
renderer;
cd;
zone;
filterService;
config;
overlayService;
/**
* Unique identifier of the component
* @group Props
*/
id;
/**
* Defines a string that labels the input for accessibility.
* @group Props
*/
ariaLabel;
/**
* Inline style of the element.
* @group Props
*/
style;
/**
* Style class of the element.
* @group Props
*/
styleClass;
/**
* Inline style of the overlay panel.
* @group Props
*/
panelStyle;
/**
* Style class of the overlay panel element.
* @group Props
*/
panelStyleClass;
/**
* Identifier of the focus input to match a label defined for the component.
* @group Props
*/
inputId;
/**
* When present, it specifies that the element should be disabled.
* @group Props
*/
disabled;
/**
* When present, it specifies that the component cannot be edited.
* @group Props
*/
readonly;
/**
* Whether to display options as grouped when nested options are provided.
* @group Props
*/
group;
/**
* When specified, displays an input field to filter the items on keyup.
* @group Props
*/
filter = true;
/**
* Defines placeholder of the filter input.
* @group Props
*/
filterPlaceHolder;
/**
* Locale to use in filtering. The default locale is the host environment's current locale.
* @group Props
*/
filterLocale;
/**
* Specifies the visibility of the options panel.
* @group Props
*/
overlayVisible;
/**
* Index of the element in tabbing order.
* @group Props
*/
tabindex = 0;
/**
* Specifies the input variant of the component.
* @group Props
*/
variant = 'outlined';
/**
* Target element to attach the overlay, valid values are "body" or a local ng-template variable of another element (note: use binding with brackets for template variables, e.g. [appendTo]="mydiv" for a div element having #mydiv as variable name).
* @group Props
*/
appendTo;
/**
* A property to uniquely identify a value in options.
* @group Props
*/
dataKey;
/**
* Name of the input element.
* @group Props
*/
name;
/**
* Establishes relationships between the component and label(s) where its value should be one or more element IDs.
* @group Props
*/
ariaLabelledBy;
/**
* Whether to show labels of selected item labels or use default label.
* @group Props
* @defaultValue true
*/
set displaySelectedLabel(val) {
this._displaySelectedLabel = val;
}
get displaySelectedLabel() {
return this._displaySelectedLabel;
}
/**
* Decides how many selected item labels to show at most.
* @group Props
* @defaultValue 3
*/
set maxSelectedLabels(val) {
this._maxSelectedLabels = val;
}
get maxSelectedLabels() {
return this._maxSelectedLabels;
}
/**
* Decides how many selected item labels to show at most.
* @group Props
*/
selectionLimit;
/**
* Label to display after exceeding max selected labels e.g. ({0} items selected), defaults "ellipsis" keyword to indicate a text-overflow.
* @group Props
*/
selectedItemsLabel;
/**
* Whether to show the checkbox at header to toggle all items at once.
* @group Props
*/
showToggleAll = true;
/**
* Text to display when filtering does not return any results.
* @group Props
*/
emptyFilterMessage = '';
/**
* Text to display when there is no data. Defaults to global value in i18n translation configuration.
* @group Props
*/
emptyMessage = '';
/**
* Clears the filter value when hiding the dropdown.
* @group Props
*/
resetFilterOnHide = false;
/**
* Icon class of the dropdown icon.
* @group Props
*/
dropdownIcon;
/**
* Name of the label field of an option.
* @group Props
*/
optionLabel;
/**
* Name of the value field of an option.
* @group Props
*/
optionValue;
/**
* Name of the disabled field of an option.
* @group Props
*/
optionDisabled;
/**
* Name of the label field of an option group.
* @group Props
*/
optionGroupLabel = 'label';
/**
* Name of the options field of an option group.
* @group Props
*/
optionGroupChildren = 'items';
/**
* Whether to show the header.
* @group Props
*/
showHeader = true;
/**
* When filtering is enabled, filterBy decides which field or fields (comma separated) to search against.
* @group Props
*/
filterBy;
/**
* Height of the viewport in pixels, a scrollbar is defined if height of list exceeds this value.
* @group Props
*/
scrollHeight = '200px';
/**
* Defines if data is loaded and interacted with in lazy manner.
* @group Props
*/
lazy = false;
/**
* Whether the data should be loaded on demand during scroll.
* @group Props
*/
virtualScroll;
/**
* Whether the multiselect is in loading state.
* @group Props
*/
loading = false;
/**
* Height of an item in the list for VirtualScrolling.
* @group Props
*/
virtualScrollItemSize;
/**
* Icon to display in loading state.
* @group Props
*/
loadingIcon;
/**
* Whether to use the scroller feature. The properties of scroller component can be used like an object in it.
* @group Props
*/
virtualScrollOptions;
/**
* Whether to use overlay API feature. The properties of overlay API can be used like an object in it.
* @group Props
*/
overlayOptions;
/**
* Defines a string that labels the filter input.
* @group Props
*/
ariaFilterLabel;
/**
* Defines how the items are filtered.
* @group Props
*/
filterMatchMode = 'contains';
/**
* Advisory information to display in a tooltip on hover.
* @group Props
*/
tooltip = '';
/**
* Position of the tooltip.
* @group Props
*/
tooltipPosition = 'right';
/**
* Type of CSS position.
* @group Props
*/
tooltipPositionStyle = 'absolute';
/**
* Style class of the tooltip.
* @group Props
*/
tooltipStyleClass;
/**
* Applies focus to the filter element when the overlay is shown.
* @group Props
*/
autofocusFilter = true;
/**
* Defines how the selected items are displayed.
* @group Props
*/
display = 'comma';
/**
* Defines the autocomplete is active.
* @group Props
*/
autocomplete = 'off';
/**
* When enabled, a clear icon is displayed to clear the value.
* @group Props
*/
showClear = false;
/**
* When present, it specifies that the component should automatically get focus on load.
* @group Props
*/
autofocus;
/**
* @deprecated since v14.2.0, use overlayOptions property instead.
* Whether to automatically manage layering.
* @group Props
*/
get autoZIndex() {
return this._autoZIndex;
}
set autoZIndex(val) {
this._autoZIndex = val;
console.warn('The autoZIndex property is deprecated since v14.2.0, use overlayOptions property instead.');
}
/**
* @deprecated since v14.2.0, use overlayOptions property instead.
* Base zIndex value to use in layering.
* @group Props
*/
get baseZIndex() {
return this._baseZIndex;
}
set baseZIndex(val) {
this._baseZIndex = val;
console.warn('The baseZIndex property is deprecated since v14.2.0, use overlayOptions property instead.');
}
/**
* Transition options of the show animation.
* @group Props
* @deprecated since v14.2.0, use overlayOptions property instead.
*/
get showTransitionOptions() {
return this._showTransitionOptions;
}
set showTransitionOptions(val) {
this._showTransitionOptions = val;
console.warn('The showTransitionOptions property is deprecated since v14.2.0, use overlayOptions property instead.');
}
/**
* Transition options of the hide animation.
* @group Props
* @deprecated since v14.2.0, use overlayOptions property instead.
*/
get hideTransitionOptions() {
return this._hideTransitionOptions;
}
set hideTransitionOptions(val) {
this._hideTransitionOptions = val;
console.warn('The hideTransitionOptions property is deprecated since v14.2.0, use overlayOptions property instead.');
}
/**
* Label to display when there are no selections.
* @group Props
* @deprecated Use placeholder instead.
*/
set defaultLabel(val) {
this._defaultLabel = val;
console.warn('defaultLabel property is deprecated since 16.6.0, use placeholder instead');
}
get defaultLabel() {
return this._defaultLabel;
}
/**
* Label to display when there are no selections.
* @group Props
*/
set placeholder(val) {
this._placeholder.set(val);
}
get placeholder() {
return this._placeholder.asReadonly();
}
/**
* An array of objects to display as the available options.
* @group Props
*/
get options() {
const options = this._options();
return options;
}
set options(val) {
if (!ObjectUtils.deepEquals(this._options(), val)) {
this._options.set(val);
}
}
/**
* When specified, filter displays with this value.
* @group Props
*/
get filterValue() {
return this._filterValue();
}
set filterValue(val) {
this._filterValue.set(val);
}
/**
* Item size of item to be virtual scrolled.
* @group Props
* @deprecated use virtualScrollItemSize property instead.
*/
get itemSize() {
return this._itemSize;
}
set itemSize(val) {
this._itemSize = val;
console.warn('The itemSize property is deprecated, use virtualScrollItemSize property instead.');
}
/**
* Whether all data is selected.
* @group Props
*/
get selectAll() {
return this._selectAll;
}
set selectAll(value) {
this._selectAll = value;
}
/**
* Indicates whether to focus on options when hovering over them, defaults to optionLabel.
* @group Props
*/
focusOnHover = false;
/**
* Fields used when filtering the options, defaults to optionLabel.
* @group Props
*/
filterFields;
/**
* Determines if the option will be selected on focus.
* @group Props
*/
selectOnFocus = false;
/**
* Whether to focus on the first visible or selected element when the overlay panel is shown.
* @group Props
*/
autoOptionFocus = true;
/**
* Callback to invoke when value changes.
* @param {MultiSelectChangeEvent} event - Custom change event.
* @group Emits
*/
onChange = new EventEmitter();
/**
* Callback to invoke when data is filtered.
* @param {MultiSelectFilterEvent} event - Custom filter event.
* @group Emits
*/
onFilter = new EventEmitter();
/**
* Callback to invoke when multiselect receives focus.
* @param {MultiSelectFocusEvent} event - Custom focus event.
* @group Emits
*/
onFocus = new EventEmitter();
/**
* Callback to invoke when multiselect loses focus.
* @param {MultiSelectBlurEvent} event - Custom blur event.
* @group Emits
*/
onBlur = new EventEmitter();
/**
* Callback to invoke when component is clicked.
* @param {Event} event - Browser event.
* @group Emits
*/
onClick = new EventEmitter();
/**
* Callback to invoke when input field is cleared.
* @group Emits
*/
onClear = new EventEmitter();
/**
* Callback to invoke when overlay panel becomes visible.
* @group Emits
*/
onPanelShow = new EventEmitter();
/**
* Callback to invoke when overlay panel becomes hidden.
* @group Emits
*/
onPanelHide = new EventEmitter();
/**
* Callback to invoke in lazy mode to load new data.
* @param {MultiSelectLazyLoadEvent} event - Lazy load event.
* @group Emits
*/
onLazyLoad = new EventEmitter();
/**
* Callback to invoke in lazy mode to load new data.
* @param {MultiSelectRemoveEvent} event - Remove event.
* @group Emits
*/
onRemove = new EventEmitter();
/**
* Callback to invoke when all data is selected.
* @param {MultiSelectSelectAllChangeEvent} event - Custom select event.
* @group Emits
*/
onSelectAllChange = new EventEmitter();
containerViewChild;
overlayViewChild;
filterInputChild;
focusInputViewChild;
itemsViewChild;
scroller;
lastHiddenFocusableElementOnOverlay;
firstHiddenFocusableElementOnOverlay;
headerCheckboxViewChild;
footerFacet;
headerFacet;
templates;
searchValue;
searchTimeout;
_selectAll = null;
_autoZIndex;
_baseZIndex;
_showTransitionOptions;
_hideTransitionOptions;
_defaultLabel;
_placeholder = signal(undefined);
_itemSize;
_selectionLimit;
_disableTooltip = false;
value;
_filteredOptions;
onModelChange = () => { };
onModelTouched = () => { };
valuesAsString;
focus;
filtered;
itemTemplate;
groupTemplate;
loaderTemplate;
headerTemplate;
filterTemplate;
footerTemplate;
emptyFilterTemplate;
emptyTemplate;
selectedItemsTemplate;
checkIconTemplate;
loadingIconTemplate;
filterIconTemplate;
removeTokenIconTemplate;
closeIconTemplate;
clearIconTemplate;
dropdownIconTemplate;
itemCheckboxIconTemplate;
headerCheckboxIconTemplate;
headerCheckboxFocus;
filterOptions;
preventModelTouched;
preventDocumentDefault;
focused = false;
itemsWrapper;
_displaySelectedLabel = true;
_maxSelectedLabels = 3;
modelValue = signal(null);
_filterValue = signal(null);
_options = signal(null);
startRangeIndex = signal(-1);
focusedOptionIndex = signal(-1);
selectedOptions;
clickInProgress = false;
get containerClass() {
return {
'p-multiselect p-component p-inputwrapper': true,
'p-disabled': this.disabled,
'p-multiselect-clearable': this.showClear && !this.disabled,
'p-multiselect-chip': this.display === 'chip',
'p-focus': this.focused,
'p-variant-filled': this.variant === 'filled' || this.config.inputStyle() === 'filled'
};
}
get inputClass() {
return {
'p-multiselect-label p-inputtext': true,
'p-placeholder': (this.placeholder() || this.defaultLabel) && (this.label() === this.placeholder() || this.label() === this.defaultLabel),
'p-multiselect-label-empty': !this.selectedItemsTemplate && (this.label() === 'p-emptylabel' || this.label().length === 0)
};
}
get panelClass() {
return {
'p-multiselect-panel p-component': true,
'p-input-filled': this.config.inputStyle() === 'filled',
'p-ripple-disabled': this.config.ripple === false
};
}
get labelClass() {
return {
'p-multiselect-label': true,
'p-placeholder': this.label() === this.placeholder() || this.label() === this.defaultLabel,
'p-multiselect-label-empty': !this.placeholder() && !this.defaultLabel && (!this.modelValue() || this.modelValue().length === 0)
};
}
get emptyMessageLabel() {
return this.emptyMessage || this.config.getTranslation(TranslationKeys.EMPTY_MESSAGE);
}
get emptyFilterMessageLabel() {
return this.emptyFilterMessage || this.config.getTranslation(TranslationKeys.EMPTY_FILTER_MESSAGE);
}
get filled() {
if (typeof this.modelValue() === 'string')
return !!this.modelValue();
return ObjectUtils.isNotEmpty(this.modelValue());
}
get isVisibleClearIcon() {
return this.modelValue() != null && this.modelValue() !== '' && ObjectUtils.isNotEmpty(this.modelValue()) && this.showClear && !this.disabled && this.filled;
}
get toggleAllAriaLabel() {
return this.config.translation.aria ? this.config.translation.aria[this.allSelected() ? 'selectAll' : 'unselectAll'] : undefined;
}
get closeAriaLabel() {
return this.config.translation.aria ? this.config.translation.aria.close : undefined;
}
get listLabel() {
return this.config.getTranslation(TranslationKeys.ARIA)['listLabel'];
}
getAllVisibleAndNonVisibleOptions() {
return this.group ? this.flatOptions(this.options) : this.options || [];
}
visibleOptions = computed(() => {
const options = this.getAllVisibleAndNonVisibleOptions();
const isArrayOfObjects = ObjectUtils.isArray(options) && ObjectUtils.isObject(options[0]);
if (this._filterValue()) {
let filteredOptions;
if (isArrayOfObjects) {
filteredOptions = this.filterService.filter(options, this.searchFields(), this._filterValue(), this.filterMatchMode, this.filterLocale);
}
else {
filteredOptions = options.filter((option) => option.toString().toLocaleLowerCase().includes(this._filterValue().toLocaleLowerCase()));
}
if (this.group) {
const optionGroups = this.options || [];
const filtered = [];
optionGroups.forEach((group) => {
const groupChildren = this.getOptionGroupChildren(group);
const filteredItems = groupChildren.filter((item) => filteredOptions.includes(item));
if (filteredItems.length > 0)
filtered.push({ ...group, [typeof this.optionGroupChildren === 'string' ? this.optionGroupChildren : 'items']: [...filteredItems] });
});
return this.flatOptions(filtered);
}
return filteredOptions;
}
return options;
});
label = computed(() => {
let label;
const modelValue = this.modelValue();
if (modelValue && modelValue.length && this.displaySelectedLabel) {
if (ObjectUtils.isNotEmpty(this.maxSelectedLabels) && modelValue.length > this.maxSelectedLabels) {
return this.getSelectedItemsLabel();
}
else {
label = '';
for (let i = 0; i < modelValue.length; i++) {
if (i !== 0) {
label += ', ';
}
label += this.getLabelByValue(modelValue[i]);
}
}
}
else {
label = this.placeholder() || this.defaultLabel || '';
}
return label;
});
chipSelectedItems = computed(() => {
return ObjectUtils.isNotEmpty(this.maxSelectedLabels) && this.modelValue() && this.modelValue().length > this.maxSelectedLabels ? this.modelValue().slice(0, this.maxSelectedLabels) : this.modelValue();
});
constructor(el, renderer, cd, zone, filterService, config, overlayService) {
this.el = el;
this.renderer = renderer;
this.cd = cd;
this.zone = zone;
this.filterService = filterService;
this.config = config;
this.overlayService = overlayService;
effect(() => {
const modelValue = this.modelValue();
const visibleOptions = this.visibleOptions();
if (visibleOptions && ObjectUtils.isNotEmpty(visibleOptions)) {
if (this.optionValue && this.optionLabel && modelValue) {
this.selectedOptions = visibleOptions.filter((option) => modelValue.includes(option[this.optionLabel]) || modelValue.includes(option[this.optionValue]));
}
else {
this.selectedOptions = modelValue;
}
this.cd.markForCheck();
}
});
}
ngOnInit() {
this.id = this.id || UniqueComponentId();
this.autoUpdateModel();
if (this.filterBy) {
this.filterOptions = {
filter: (value) => this.onFilterInputChange(value),
reset: () => this.resetFilter()
};
}
}
maxSelectionLimitReached() {
return this.selectionLimit && this.modelValue() && this.modelValue().length === this.selectionLimit;
}
ngAfterContentInit() {
this.templates.forEach((item) => {
switch (item.getType()) {
case 'item':
this.itemTemplate = item.template;
break;
case 'group':
this.groupTemplate = item.template;
break;
case 'selectedItems':
this.selectedItemsTemplate = item.template;
break;
case 'header':
this.headerTemplate = item.template;
break;
case 'filter':
this.filterTemplate = item.template;
break;
case 'emptyfilter':
this.emptyFilterTemplate = item.template;
break;
case 'empty':
this.emptyTemplate = item.template;
break;
case 'footer':
this.footerTemplate = item.template;
break;
case 'loader':
this.loaderTemplate = item.template;
break;
case 'checkicon':
this.checkIconTemplate = item.template;
console.warn('checkicon is deprecated and will removed in v18. Use itemcheckboxicon or headercheckboxicon templates instead.');
break;
case 'headercheckboxicon':
this.headerCheckboxIconTemplate = item.template;
break;
case 'loadingicon':
this.loadingIconTemplate = item.template;
break;
case 'filtericon':
this.filterIconTemplate = item.template;
break;
case 'removetokenicon':
this.removeTokenIconTemplate = item.template;
break;
case 'closeicon':
this.closeIconTemplate = item.template;
break;
case 'clearicon':
this.clearIconTemplate = item.template;
break;
case 'dropdownicon':
this.dropdownIconTemplate = item.template;
break;
case 'itemcheckboxicon':
this.itemCheckboxIconTemplate = item.template;
break;
default:
this.itemTemplate = item.template;
break;
}
});
}
ngAfterViewInit() {
if (this.overlayVisible) {
this.show();
}
}
ngAfterViewChecked() {
if (this.filtered) {
this.zone.runOutsideAngular(() => {
setTimeout(() => {
this.overlayViewChild?.alignOverlay();
}, 1);
});
this.filtered = false;
}
}
flatOptions(options) {
return (options || []).reduce((result, option, index) => {
result.push({ optionGroup: option, group: true, index });
const optionGroupChildren = this.getOptionGroupChildren(option);
optionGroupChildren && optionGroupChildren.forEach((o) => result.push(o));
return result;
}, []);
}
autoUpdateModel() {
if (this.selectOnFocus && this.autoOptionFocus && !this.hasSelectedOption()) {
this.focusedOptionIndex.set(this.findFirstFocusedOptionIndex());
const value = this.getOptionValue(this.visibleOptions()[this.focusedOptionIndex()]);
this.onOptionSelect({ originalEvent: null, option: [value] });
}
}
/**
* Updates the model value.
* @group Method
*/
updateModel(value, event) {
this.value = value;
this.onModelChange(value);
this.modelValue.set(value);
}
onInputClick(event) {
event.stopPropagation();
event.preventDefault();
this.focusedOptionIndex.set(-1);
}
onOptionSelect(event, isFocus = false, index = -1) {
const { originalEvent, option } = event;
if (this.disabled || this.isOptionDisabled(option)) {
return;
}
let selected = this.isSelected(option);
let value = null;
if (selected) {
value = this.modelValue().filter((val) => !ObjectUtils.equals(val, this.getOptionValue(option), this.equalityKey()));
this.onRemove.emit({ newValue: this.value, removed: this.getOptionValue(option) });
}
else {
value = [...(this.modelValue() || []), this.getOptionValue(option)];
}
this.updateModel(value, originalEvent);
index !== -1 && this.focusedOptionIndex.set(index);
isFocus && DomHandler.focus(this.focusInputViewChild?.nativeElement);
this.onChange.emit({
originalEvent: event,
value: value,
itemValue: option
});
}
findSelectedOptionIndex() {
return this.hasSelectedOption() ? this.visibleOptions().findIndex((option) => this.isValidSelectedOption(option)) : -1;
}
onOptionSelectRange(event, start = -1, end = -1) {
start === -1 && (start = this.findNearestSelectedOptionIndex(end, true));
end === -1 && (end = this.findNearestSelectedOptionIndex(start));
if (start !== -1 && end !== -1) {
const rangeStart = Math.min(start, end);
const rangeEnd = Math.max(start, end);
const value = this.visibleOptions()
.slice(rangeStart, rangeEnd + 1)
.filter((option) => this.isValidOption(option))
.map((option) => this.getOptionValue(option));
this.updateModel(value, event);
}
}
searchFields() {
return (this.filterBy || this.optionLabel || 'label').split(',');
}
findNearestSelectedOptionIndex(index, firstCheckUp = false) {
let matchedOptionIndex = -1;
if (this.hasSelectedOption()) {
if (firstCheckUp) {
matchedOptionIndex = this.findPrevSelectedOptionIndex(index);
matchedOptionIndex = matchedOptionIndex === -1 ? this.findNextSelectedOptionIndex(index) : matchedOptionIndex;
}
else {
matchedOptionIndex = this.findNextSelectedOptionIndex(index);
matchedOptionIndex = matchedOptionIndex === -1 ? this.findPrevSelectedOptionIndex(index) : matchedOptionIndex;
}
}
return matchedOptionIndex > -1 ? matchedOptionIndex : index;
}
findPrevSelectedOptionIndex(index) {
const matchedOptionIndex = this.hasSelectedOption() && index > 0 ? ObjectUtils.findLastIndex(this.visibleOptions().slice(0, index), (option) => this.isValidSelectedOption(option)) : -1;
return matchedOptionIndex > -1 ? matchedOptionIndex : -1;
}
findFirstFocusedOptionIndex() {
const selectedIndex = this.findFirstSelectedOptionIndex();
return selectedIndex < 0 ? this.findFirstOptionIndex() : selectedIndex;
}
findFirstOptionIndex() {
return this.visibleOptions().findIndex((option) => this.isValidOption(option));
}
findFirstSelectedOptionIndex() {
return this.hasSelectedOption() ? this.visibleOptions().findIndex((option) => this.isValidSelectedOption(option)) : -1;
}
findNextSelectedOptionIndex(index) {
const matchedOptionIndex = this.hasSelectedOption() && index < this.visibleOptions().length - 1
? this.visibleOptions()
.slice(index + 1)
.findIndex((option) => this.isValidSelectedOption(option))
: -1;
return matchedOptionIndex > -1 ? matchedOptionIndex + index + 1 : -1;
}
equalityKey() {
return this.optionValue ? null : this.dataKey;
}
hasSelectedOption() {
return ObjectUtils.isNotEmpty(this.modelValue());
}
isValidSelectedOption(option) {
return this.isValidOption(option) && this.isSelected(option);
}
isOptionGroup(option) {
return (this.group || this.optionGroupLabel) && option.optionGroup && option.group;
}
isValidOption(option) {
return option && !(this.isOptionDisabled(option) || this.isOptionGroup(option));
}
isOptionDisabled(option) {
if (this.maxSelectionLimitReached() && !this.isSelected(option)) {
return true;
}
return this.optionDisabled ? ObjectUtils.resolveFieldData(option, this.optionDisabled) : option && option.disabled !== undefined ? option.disabled : false;
}
isSelected(option) {
const optionValue = this.getOptionValue(option);
return (this.modelValue() || []).some((value) => ObjectUtils.equals(value, optionValue, this.equalityKey()));
}
isOptionMatched(option) {
return this.isValidOption(option) && this.getOptionLabel(option).toString().toLocaleLowerCase(this.filterLocale).startsWith(this.searchValue.toLocaleLowerCase(this.filterLocale));
}
isEmpty() {
return !this._options() || (this.visibleOptions() && this.visibleOptions().length === 0);
}
getOptionIndex(index, scrollerOptions) {
return this.virtualScrollerDisabled ? index : scrollerOptions && scrollerOptions.getItemOptions(index)['index'];
}
getAriaPosInset(index) {
return ((this.optionGroupLabel
? index -
this.visibleOptions()
.slice(0, index)
.filter((option) => this.isOptionGroup(option)).length
: index) + 1);
}
get ariaSetSize() {
return this.visibleOptions().filter((option) => !this.isOptionGroup(option)).length;
}
getLabelByValue(value) {
const options = this.group ? this.flatOptions(this._options()) : this._options() || [];
const matchedOption = options.find((option) => !this.isOptionGroup(option) && ObjectUtils.equals(this.getOptionValue(option), value, this.equalityKey()));
return matchedOption ? this.getOptionLabel(matchedOption) : null;
}
getSelectedItemsLabel() {
let pattern = /{(.*?)}/;
let message = this.selectedItemsLabel ? this.selectedItemsLabel : this.config.getTranslation(TranslationKeys.SELECTION_MESSAGE);
if (pattern.test(message)) {
return message.replace(message.match(pattern)[0], this.modelValue().length + '');
}
return message;
}
getOptionLabel(option) {
return this.optionLabel ? ObjectUtils.resolveFieldData(option, this.optionLabel) : option && option.label != undefined ? option.label : option;
}
getOptionValue(option) {
return this.optionValue ? ObjectUtils.resolveFieldData(option, this.optionValue) : !this.optionLabel && option && option.value !== undefined ? option.value : option;
}
getOptionGroupLabel(optionGroup) {
return this.optionGroupLabel ? ObjectUtils.resolveFieldData(optionGroup, this.optionGroupLabel) : optionGroup && optionGroup.label != undefined ? optionGroup.label : optionGroup;
}
getOptionGroupChildren(optionGroup) {
return this.optionGroupChildren ? ObjectUtils.resolveFieldData(optionGroup, this.optionGroupChildren) : optionGroup.items;
}
onKeyDown(event) {
if (this.disabled) {
event.preventDefault();
return;
}
const metaKey = event.metaKey || event.ctrlKey;
switch (event.code) {
case 'ArrowDown':
this.onArrowDownKey(event);
break;
case 'ArrowUp':
this.onArrowUpKey(event);
break;
case 'Home':
this.onHomeKey(event);
break;
case 'End':
this.onEndKey(event);
break;
case 'PageDown':
this.onPageDownKey(event);
break;
case 'PageUp':
this.onPageUpKey(event);
break;
case 'Enter':
case 'Space':
this.onEnterKey(event);
break;
case 'Escape':
this.onEscapeKey(event);
break;
case 'Tab':
this.onTabKey(event);
break;
case 'ShiftLeft':
case 'ShiftRight':
this.onShiftKey();
break;
default:
if (event.code === 'KeyA' && metaKey) {
const value = this.visibleOptions()
.filter((option) => this.isValidOption(option))
.map((option) => this.getOptionValue(option));
this.updateModel(value, event);
event.preventDefault();
break;
}
if (!metaKey && ObjectUtils.isPrintableCharacter(event.key)) {
!this.overlayVisible && this.show();
this.searchOptions(event, event.key);
event.preventDefault();
}
break;
}
}
onFilterKeyDown(event) {
switch (event.code) {
case 'ArrowDown':
this.onArrowDownKey(event);
break;
case 'ArrowUp':
this.onArrowUpKey(event, true);
break;
case 'ArrowLeft':
case 'ArrowRight':
this.onArrowLeftKey(event, true);
break;
case 'Home':
this.onHomeKey(event, true);
break;
case 'End':
this.onEndKey(event, true);
break;
case 'Enter':
case 'NumpadEnter':
this.onEnterKey(event);
break;
case 'Escape':
this.onEscapeKey(event);
break;
case 'Tab':
this.onTabKey(event, true);
break;
default:
break;
}
}
onArrowLeftKey(event, pressedInInputText = false) {
pressedInInputText && this.focusedOptionIndex.set(-1);
}
onArrowDownKey(event) {
const optionIndex = this.focusedOptionIndex() !== -1 ? this.findNextOptionIndex(this.focusedOptionIndex()) : this.findFirstFocusedOptionIndex();
if (event.shiftKey) {
this.onOptionSelectRange(event, this.startRangeIndex(), optionIndex);
}
this.changeFocusedOptionIndex(event, optionIndex);
!this.overlayVisible && this.show();
event.preventDefault();
event.stopPropagation();
}
onArrowUpKey(event, pressedInInputText = false) {
if (event.altKey && !pressedInInputText) {
if (this.focusedOptionIndex() !== -1) {
this.onOptionSelect(event, this.visibleOptions()[this.focusedOptionIndex()]);
}
this.overlayVisible && this.hide();
event.preventDefault();
}
else {
const optionIndex = this.focusedOptionIndex() !== -1 ? this.findPrevOptionIndex(this.focusedOptionIndex()) : this.findLastFocusedOptionIndex();
if (event.shiftKey) {
this.onOptionSelectRange(event, optionIndex, this.startRangeIndex());
}
this.changeFocusedOptionIndex(event, optionIndex);
!this.overlayVisible && this.show();
event.preventDefault();
}
event.stopPropagation();
}
onHomeKey(event, pressedInInputText = false) {
const { currentTarget } = event;
if (pressedInInputText) {
const len = currentTarget.value.length;
currentTarget.setSelectionRange(0, event.shiftKey ? len : 0);
this.focusedOptionIndex.set(-1);
}
else {
let metaKey = event.metaKey || event.ctrlKey;
let optionIndex = this.findFirstOptionIndex();
if (event.shiftKey && metaKey) {
this.onOptionSelectRange(event, optionIndex, this.startRangeIndex());
}
this.changeFocusedOptionIndex(event, optionIndex);
!this.overlayVisible && this.show();
}
event.preventDefault();
}
onEndKey(event, pressedInInputText = false) {
const { currentTarget } = event;
if (pressedInInputText) {
const len = currentTarget.value.length;
currentTarget.setSelectionRange(event.shiftKey ? 0 : len, len);
this.focusedOptionIndex.set(-1);
}
else {
let metaKey = event.metaKey || event.ctrlKey;
let optionIndex = this.findLastFocusedOptionIndex();
if (event.shiftKey && metaKey) {
this.onOptionSelectRange(event, this.startRangeIndex(), optionIndex);
}
this.changeFocusedOptionIndex(event, optionIndex);
!this.overlayVisible && this.show();
}
event.preventDefault();
}
onPageDownKey(event) {
this.scrollInView(this.visibleOptions().length - 1);
event.preventDefault();
}
onPageUpKey(event) {
this.scrollInView(0);
event.preventDefault();
}
onEnterKey(event) {
if (!this.overlayVisible) {
this.onArrowDownKey(event);
}
else {
if (this.focusedOptionIndex() !== -1) {
if (event.shiftKey) {
this.onOptionSelectRange(event, this.focusedOptionIndex());
}
else {
this.onOptionSelect({ originalEvent: event, option: this.visibleOptions()[this.focusedOptionIndex()] });
}
}
}
event.preventDefault();
}
onEscapeKey(event) {
this.overlayVisible && this.hide(true);
event.preventDefault();
}
onDeleteKey(event) {
if (this.showClear) {
this.clear(event);
event.preventDefault();
}
}
onTabKey(event, pressedInInputText = false) {
if (!pressedInInputText) {
if (this.overlayVisible && this.hasFocusableElements()) {
DomHandler.focus(event.shiftKey ? this.lastHiddenFocusableElementOnOverlay.nativeElement : this.firstHiddenFocusableElementOnOverlay.nativeElement);
event.preventDefault();
}
else {
if (this.focusedOptionIndex() !== -1) {
this.onOptionSelect({ originalEvent: event, option: this.visibleOptions()[this.focusedOptionIndex()] });
}
this.overlayVisible && this.hide(this.filter);
}
}
}
onShiftKey() {
this.startRangeIndex.set(this.focusedOptionIndex());
}
onContainerClick(event) {
if (this.disabled || this.loading || this.readonly || event.target.isSameNode(this.focusInputViewChild?.nativeElement)) {
return;
}
if (event.target.tagName === 'INPUT' || event.target.getAttribute('data-pc-section') === 'clearicon' || event.target.closest('[data-pc-section="clearicon"]')) {
event.preventDefault();
return;
}
else if (!this.overlayViewChild || !this.overlayViewChild.el.nativeElement.contains(event.target)) {
if (this.clickInProgress) {
return;
}
this.clickInProgress = true;
setTimeout(() => {