Search code examples
angulartypescriptlabelmulti-select

How to add an extra label in a multiselect component in PrimeNg?


I have a multiselect primeNg component which is fiiling dinamicaly after a server request:

<p-multiSelect
    [options]="multiselectDisplayOptions"
    [(ngModel)]="selectedValues"
    [optionLabel]="columnToDisplay.reference"
    [selectionLimit]="selectedLimitOne"
    display="chip"
    [showHeader]=false
    (onChange)="onChange($event.value)"
    (onClick)="onClick()"
    appendTo="body"
    [required]="isRequired">
</p-multiSelect>

In the main component, I have data binding for these @Input()s, and I want to choose "All sites" from here: enter image description here

and the last option should be "All Sites" without select all sites from the multi-select component. The option "All Sites" won't be a record in the database.


Solution

  • This is my example, use this and adapt styles and logic for youself:

    What to look for:

    1. named your multiselect #multiselect
    2. set [filter]="false" [showToggleAll]="false" to remove base input and checkbox
    3. in content of multiselect use <ng-template> to customize it
    4. in <ng-template pTemplate="header"> add logic for custom checkbox <p-checkbox (onChange)="multiselect.allChecked ? multiselect.uncheckAll() : multiselect.checkAll()"></p-checkbox>

    HTML:

    <p-multiSelect #multiselect [filter]="false" [showToggleAll]="false" [options]="countries" [(ngModel)]="selectedCountries" defaultLabel="Select a Country" optionLabel="name" class="multiselect-custom">
        <ng-template pTemplate="header">
          <p-checkbox (onChange)="multiselect.allChecked ? multiselect.uncheckAll() : multiselect.checkAll()"></p-checkbox>
          All countries
        </ng-template>
        <ng-template let-value pTemplate="selectedItems">
          <div class="country-item country-item-value" *ngFor="let option of selectedCountries">
            <div>{{option.name}}</div>
          </div>
          <div *ngIf="!selectedCountries || selectedCountries.length === 0" class="country-placeholder">
            Select Countries
          </div>
        </ng-template>
        <ng-template let-country pTemplate="item">
          <div class="country-item">
            <div>{{country.name}}</div>
          </div>
        </ng-template>
      </p-multiSelect>
    

    TS:

    countries: Country[];
    
      selectedCountries: Country[] = [];
    
      constructor() {
        this.countries = [
          {name: 'Australia', code: 'AU'},
          {name: 'Brazil', code: 'BR'},
          {name: 'China', code: 'CN'},
          {name: 'Egypt', code: 'EG'},
          {name: 'France', code: 'FR'},
          {name: 'Germany', code: 'DE'},
          {name: 'India', code: 'IN'},
          {name: 'Japan', code: 'JP'},
          {name: 'Spain', code: 'ES'},
          {name: 'United States', code: 'US'}
        ];
      }