To achieve this functionality, we can utilize a combination of HTML, CSS, and logic. Here are the styles that can be applied: create a custom class called custom-grouped-dropdown
and scope it specifically to the dropdown by using ::ng-deep
to make it visible to all contents of the component.
::ng-deep .custom-grouped-dropdown {
p-dropdownitem {
padding: 0px !important;
display: block;
}
.p-dropdown-item {
padding: 0 !important;
}
}
Additionally, we can use a property called hidden
for each item in the group to control data visibility with the help of *ngIf
. A button can also be added to toggle this functionality.
<br /><br /><br />
<p-dropdown
class="custom-grouped-dropdown"
[options]="groupOptions"
[(ngModel)]="selectedGroup"
placeholder="Select"
[group]="true"
>
<ng-template let-group pTemplate="group">
<div class="flex align-items-center justify-content-between">
<span>{{ group.label }}</span>
<button (click)="toggle(group)">{{!group.hidden ? '+' : '-'}}</button>
</div>
</ng-template>
<ng-template let-item pTemplate="item">
<div
class="flex align-items-center"
*ngIf="item.hidden"
style="padding: 0.75rem 1.25rem !important"
>
<span>{{ item.label }}</span>
</div>
</ng-template>
</p-dropdown>
Finally, a function has been implemented to update all the children's hidden
flag based on the toggle action. Note that Primeng only supports single-level grouping, so recursion was not implemented in this case.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'dropdown-basic-demo',
templateUrl: './dropdown-basic-demo.html',
styleUrls: ['./dropdown-basic-demo.scss'],
})
export class DropdownBasicDemo {
selectedGroup = null;
groupOptions = [
{
value: '1',
label: 'AA',
items: [
{ value: '31', label: 'CC1' },
{ value: '32', label: 'CC2' },
{ value: '33', label: 'CC3' },
],
},
{
value: '2',
label: 'BB',
items: [
{ value: '31', label: 'CC1' },
{ value: '32', label: 'CC2' },
{ value: '33', label: 'CC3' },
],
},
{
label: 'CC',
value: '3',
items: [
{ value: '31', label: 'CC1' },
{ value: '32', label: 'CC2' },
{ value: '33', label: 'CC3' },
],
},
];
toggle(group: any) {
console.log(group);
if (group?.items.length) {
group.items.forEach((item: any) => (item.hidden = !item.hidden));
group.hidden = !!group.items[0].hidden;
}
}
}