MultiSelectMultiSelect is used to select multiple items from a collection.

MultiSelect - 图1

Documentation

CDK

Virtual Scrolling enabled MultiSelect depends on @angular/cdk's ScrollingModule so begin with installing CDK if not already installed.

  1. npm install @angular/cdk --save
  2.  

Import

  1. import {MultiSelectModule} from 'primeng/multiselect';
  2.  

Getting Started

MultiSelect requires a value to bind and a collection of options. There are two alternatives of how to define the options property; one way is providing a collection of SelectItem instances whereas other way is providing an array of arbitrary objects along with the optionLabel property to specify the field name of the option. SelectItem API is designed to have more control on how the options are displayed such as grouping and disabling however in most cases an arbitrary object collection will suffice. Example below demonstrates both cases.

  1. <p-multiSelect [options]="cities1" [(ngModel)]="selectedCities1"></p-multiSelect>
  2. <p-multiSelect [options]="cities2" [(ngModel)]="selectedCities2" optionLabel="name"></p-multiSelect>
  3.  
  1. import {SelectItem} from 'primeng/api';
  2. interface City {
  3. name: string,
  4. code: string
  5. }
  6. export class MyModel {
  7. cities1: SelectItem[];
  8. cities2: City[];
  9. selectedCities1: City[];
  10. selectedCities2: City[];
  11. constructor() {
  12. //SelectItem API with label-value pairs
  13. this.cities1 = [
  14. {label:'New York', value:{id:1, name: 'New York', code: 'NY'}},
  15. {label:'Rome', value:{id:2, name: 'Rome', code: 'RM'}},
  16. {label:'London', value:{id:3, name: 'London', code: 'LDN'}},
  17. {label:'Istanbul', value:{id:4, name: 'Istanbul', code: 'IST'}},
  18. {label:'Paris', value:{id:5, name: 'Paris', code: 'PRS'}}
  19. ];
  20. //An array of cities
  21. this.cities2 = [
  22. {name: 'New York', code: 'NY'},
  23. {name: 'Rome', code: 'RM'},
  24. {name: 'London', code: 'LDN'},
  25. {name: 'Istanbul', code: 'IST'},
  26. {name: 'Paris', code: 'PRS'}
  27. ];
  28. }
  29. }
  30.  

Model Driven Forms

MultiSelect can be used in a model driven form as well.

  1. <p-multiSelect [options]="cities" formControlName="selectedCities"></p-multiSelect>
  2.  

Disabled Options

Particular options can be prevented from selection using the disabled property of SelectItem API.

Templating

Label of a selectitem is displayed by default next to the checkbox in the overlay panel and it is possible to customize the content using templating. The ngTemplate receives the selectitem as the implicit variable.

In addition selectedItems template can be used to customize the selected values display instead of the default comma separated list.

  1. <p-multiSelect [options]="cars" [(ngModel)]="selectedCars2" [panelStyle]="{minWidth:'12em'}">
  2. <ng-template let-selectedCars pTemplate="selectedItems">
  3. <span *ngFor="let selectedCar of selectedCars">{{car.brand}}</span>
  4. </ng-template>
  5. <ng-template let-car let-i="index" pTemplate="item">
  6. {{i}}
  7. <img src="assets/showcase/images/demo/car/{{car.label}}.png" style="width:24px;display:inline-block;vertical-align:middle"/>
  8. <div style="font-size:14px;float:right;margin-top:4px">{{car.label}}</div>
  9. </ng-template>
  10. </p-multiSelect>
  11. <p>Selected Cars: {{selectedCars2}}</p>
  12.  

Filtering

Options can be filtered using an input field in the overlay by enabling the filter property. By default filtering is done against label of the SelectItem and filterBy property is available to choose one or more properties of the SelectItem API.

  1. <p-multiSelect [options]="cities" [(ngModel)]="selectedCities" [filter]="true"></p-multiSelect>
  2. <p-multiSelect [options]="cities" [(ngModel)]="selectedCities" [filter]="true" filterBy="label,value.name"></p-multiSelect>
  3.  

Change Detection

MultiSelect detects changes to options and selected values using setters so when changing your model, prefer creating a new array reference instead of manipulating an existing array.

p-header and p-footer elements can be used display custom content inside the header and footer sections.

  1. <p-multiSelect [options]="cities" formControlName="selectedCities">
  2. <p-header>
  3. //Header content
  4. </p-header>
  5. <p-footer>
  6. //Footer content
  7. </p-footer>
  8. </p-multiSelect>
  9.  

Virtual Scrolling

VirtualScrolling is an efficient way of rendering the options by displaying a small subset of data in the viewport at any time. When dealing with huge number of options, it is suggested to enable VirtualScrolling to avoid performance issues. Usage is simple as setting virtualScroll property to true and defining itemSize to specify the height of an item.

  1. <p-multiSelect [options]="cities" formControlName="selectedCities" [virtualScroll]="true" itemSize="30"></p-multiSelect>
  2.  

Animation Configuration

Transition of the open and hide animations can be customized using the showTransitionOptions and hideTransitionOptions properties, example below disables the animations altogether.

  1. <p-multiSelect [options]="cities" formControlName="selectedCities" [showTransitionOptions]="'0ms'" [hideTransitionOptions]="'0ms'"></p-multiSelect>
  2.  

Properties

NameTypeDefaultDescription
optionsarraynullAn array of objects to display as the available options.
optionLabelstringnullName of the label field of an option when an arbitrary objects instead of SelectItems are used as options.
disabledbooleanfalseWhen present, it specifies that the element should be disabled.
readonlybooleanfalseWhen present, it specifies that the component cannot be edited.
filterbooleantrueWhen specified, displays an input field to filter the items on keyup.
filterBystringlabelWhen filtering is enabled, filterBy decides which field or fields (comma separated) to search against.
filterPlaceHolderstringnullDefines placeholder of the filter input.
defaultLabelstringChooseLabel to display when there are no selections.
appendToanynullTarget element to attach the overlay, valid values are "body" or a local ng-template variable of another element.
styleobjectnullInline style of the element.
styleClassstringnullStyle class of the element.
panelStyleobjectnullInline style of the overlay panel.
panelStyleClassstringnullStyle class of the overlay panel.
scrollHeightstring200pxHeight of the viewport in pixels, a scrollbar is defined if height of list exceeds this value.
overlayVisiblebooleanfalseSpecifies the visibility of the options panel.
tabindexnumbernullIndex of the element in tabbing order.
dataKeystringnullA property to uniquely identify a value in options.
namestringnullName of the input element.
inputIdstringnullIdentifier of the focus input to match a label defined for the component.
displaySelectedLabelbooleantrueWhether to show labels of selected item labels or use default label.
maxSelectedLabelsnumber3Decides how many selected item labels to show at most.
selectedItemsLabelstring{0} items selectedLabel to display after exceeding max selected labels.
showToggleAllbooleantrueWhether to show the checkbox at header to toggle all items at once.
resetFilterOnHidebooleanfalseClears the filter value when hiding the dropdown.
dropdownIconstringpi pi-chevron-downIcon class of the dropdown icon.
showHeaderbooleantrueWhether to show the header.
selectionLimitnumbernullNumber of maximum options that can be selected.
baseZIndexnumber0Base zIndex value to use in layering.
autoZIndexbooleantrueWhether to automatically manage layering.
showTransitionOptionsstring225ms ease-outTransition options of the show animation.
hideTransitionOptionsstring195ms ease-inTransition options of the hide animation.
itemSizenumbernullHeight of an item in the list for VirtualScrolling.
virtualScrollbooleanfalseWhether the data should be loaded on demand during scroll.
ariaFilterLabelstringnullDefines a string that labels the filter input.

Events

NameParametersDescription
onClickevent: Click eventCallback to invoke when component is clicked.
onChangeevent.originalEvent: browser event event.value: Current selected values event.itemValue: Toggled item value Callback to invoke when value changes.
onFocusevent.originalEvent: browser eventCallback to invoke when multiselect receives focus.
onBlurevent.originalEvent: browser eventCallback to invoke when multiselect loses focus.
onPanelShow-Callback to invoke when overlay panel becomes visible.
onPanelHide-Callback to invoke when overlay panel becomes hidden.

Styling

Following is the list of structural style classes, for theming classes visit theming page.

NameElement
ui-multiselectContainer element.
ui-multiselect-label-containerContainer of the label to display selected items.
ui-multiselect-labelLabel to display selected items.
ui-multiselect-triggerDropdown button.
ui-multiselect-filter-containerContainer of filter input.
ui-multiselect-panelOverlay panel for items.
ui-multiselect-itemsList container of items.
ui-multiselect-itemAn item in the list.
ui-multiselect-openContainer element when overlay is visible.

Dependencies

Angular CDK.

Source

View on GitHub

  1. <h3 class="first">Basic</h3>
  2. <p-multiSelect [options]="cars" [(ngModel)]="selectedCars1" [panelStyle]="{minWidth:'12em'}"></p-multiSelect>
  3. <p>Selected Cars: {{selectedCars1}}</p>
  4. <h3>Template</h3>
  5. <p-multiSelect [options]="cars" [(ngModel)]="selectedCars2" [panelStyle]="{minWidth:'12em'}">
  6. <ng-template let-value pTemplate="selectedItems">
  7. <div *ngFor="let val of value" class="ui-multiselected-item-token ui-corner-all">
  8. <img src="assets/showcase/images/demo/car/{{val}}.png" style="width:20px;vertical-align:middle;margin-right:.5em" />
  9. <span>{{val}}</span>
  10. </div>
  11. <span *ngIf="!value || value.length === 0" class="ui-multiselected-empty-token ui-corner-all">Choose</span>
  12. </ng-template>
  13. <ng-template let-car pTemplate="item">
  14. <img src="assets/showcase/images/demo/car/{{car.label}}.png" style="width:24px;display:inline-block;vertical-align:middle"/>
  15. <div style="font-size:14px;float:right;margin-top:4px">{{car.label}}</div>
  16. </ng-template>
  17. </p-multiSelect>
  18. <p>Selected Cars: {{selectedCars2}}</p>
  19. <h3>Virtual Scroll (10000 Items)</h3>
  20. <p-multiSelect [options]="items" [(ngModel)]="item" [panelStyle]="{minWidth:'12em'}" [virtualScroll]="true" [itemSize]="34" [filter]="false"></p-multiSelect>
  21.  
  1. @Component({
  2. templateUrl: './multiselectdemo.html',
  3. styles: [`
  4. :host ::ng-deep .ui-multiselected-item-token,
  5. :host ::ng-deep .ui-multiselected-empty-token {
  6. padding: 2px 4px;
  7. margin: 0 0.286em 0 0;
  8. display: inline-block;
  9. vertical-align:middle;
  10. height: 1.857em;
  11. }
  12. :host ::ng-deep .ui-multiselected-item-token {
  13. background: #007ad9;
  14. color: #ffffff;
  15. }
  16. :host ::ng-deep .ui-multiselected-empty-token {
  17. background: #d95f00;
  18. color: #ffffff;
  19. }
  20. `]
  21. })
  22. export class MultiSelectDemo {
  23. cars: SelectItem[];
  24. selectedCars1: string[] = [];
  25. selectedCars2: string[] = [];
  26. items: SelectItem[];
  27. item: string;
  28. constructor() {
  29. this.cars = [
  30. {label: 'Audi', value: 'Audi'},
  31. {label: 'BMW', value: 'BMW'},
  32. {label: 'Fiat', value: 'Fiat'},
  33. {label: 'Ford', value: 'Ford'},
  34. {label: 'Honda', value: 'Honda'},
  35. {label: 'Jaguar', value: 'Jaguar'},
  36. {label: 'Mercedes', value: 'Mercedes'},
  37. {label: 'Renault', value: 'Renault'},
  38. {label: 'VW', value: 'VW'},
  39. {label: 'Volvo', value: 'Volvo'},
  40. ];
  41. this.items = [];
  42. for (let i = 0; i < 10000; i++) {
  43. this.items.push({label: 'Item ' + i, value: 'Item ' + i});
  44. }
  45. }
  46. }
  47.