If I have the following dropdown, how can I select the first item if there is only 1 element in the filteredGroupNames
then disable the dropdown and don't display the placeholder
<ng-template pTemplate="content">
<div >
<label>Name</label>
<p-dropdown [(ngModel)]="newOrSelectedGroupName" [options]="filteredGroupNames" [showClear]="true"
placeholder="Select a group"
></p-dropdown>
</div>
</ng-template>
CodePudding user response:
Looks like optionDisabled
is an available attribute for PrimeNG dropdowns. You can set it to be conditionally disabled based on the length of filteredGroupNames
. Something like the following:
<p-dropdown [(ngModel)]="newOrSelectedGroupName"
[options]="filteredGroupNames" [showClear]="true"
placeholder="Select a group"
[optionDisabled]="filteredGroupNames.length > 1 ? 'inactive' : 'active'"
></p-dropdown>
CodePudding user response:
In your component.html
file
<ng-template pTemplate="content">
<div >
<label>Name</label>
<p-dropdown [(ngModel)]="newOrSelectedGroupName" [options]="filteredGroupNames"
[showClear]="filteredGroupNames.length!=1" placeholder="Select a group" [class.disabled]="filteredGroupNames.length==1"
></p-dropdown>
</div>
</ng-template>
In your component.ts file
newOrSelectedGroupName;
ngOnInit():void {
if(filteredGroupNames.lengh==1) {
this.newOrSelectedGroupName=filteredGroupNames[0].value;
}
}
I have assumed the value
key is present in the object filteredGroupNames
and it is binded as value to the dropdown in your HTML like optionValue="value"
.
Sample object is
filteredGroupNames = [
{
name:'name 1',
value:1
}
];
In your styles.scss
or styles.css
.disabled .p-dropdown-panel,
.disabled .p-dropdown-trigger {
display: none;
}
.disabled.p-inputwrapper-focus .p-dropdown {
border-color: #ced4da !important;
box-shadow: none !important;
}