PrimeNG dropdown - disable certain SelectItems

cookya picture cookya · May 9, 2017 · Viewed 16k times · Source

Is there an option to disable some of PrimeNG's dropdown items (SelectItems)?

I notice this discussion, is something changed?

Answer

Shubhashish Mishra picture Shubhashish Mishra · Mar 22, 2018

You can also disable any item in primeng dropdown using ng-template, click event and custom style as below:

    cars: any[];
    selectedCar: string;
  1. Initialize the cars array of object that is essentially an extension of Interface SelectItem with added property disabled: boolean

     ngOnInit(): void {
      this.cars = [];
      this.cars.push({label: 'Audi', value: 'Audi'});
      this.cars.push({label: 'BMW', value: 'BMW'});
      this.cars.push({label: 'Fiat', value: 'Fiat', disabled: true});
      this.cars.push({label: 'Ford', value: 'Ford'});
      this.cars.push({label: 'Honda', value: 'Honda', disabled: true});
      this.cars.push({label: 'Jaguar', value: 'Jaguar'});
      this.cars.push({label: 'Mercedes', value: 'Mercedes'});
      this.cars.push({label: 'Renault', value: 'Renault'});
      this.cars.push({label: 'VW', value: 'VW'});
      this.cars.push({label: 'Volvo', value: 'Volvo'});
     }
    
  2. Method that gets triggered on click event

     onClick(disabled: boolean) {
             if(disabled) {
                 event.stopPropagation();
             }
         }
    
  3. Customizing the Primeng Dropdown using ng-template and adding ng-style

     <p-dropdown [options]="cars" [(ngModel)]="selectedCar" [style]="{'width':'150px'}">
             <ng-template let-option pTemplate="item">
                 <div>
                     <div (click)="onClick(option.disabled)" [ngStyle]="option.disabled? {'color': '#ccc', 'cursor': 'default'} : ''"> {{option.label}} </div>
                 </div>
             </ng-template>
         </p-dropdown>
    

Credit: ogousa (primeng forum)