如果我有以下下拉列表,如果
filteredGroupNames
中只有 1 个元素,如何选择第一项,然后禁用下拉列表并且不显示 placeholder
<ng-template pTemplate="content">
<div class="field">
<label>Name</label>
<p-dropdown [(ngModel)]="newOrSelectedGroupName" [options]="filteredGroupNames" [showClear]="true"
placeholder="Select a group"
></p-dropdown>
</div>
</ng-template>
<p-dropdown [(ngModel)]="newOrSelectedGroupName" [options]="filteredGroupNames" [showClear]="filteredGroupNames.length !== 1"
[optionValue]="getOptionValue()"
placeholder="filteredGroupNames.length === 1 ? '' : 'Select a group'"
[disabled]="filteredGroupNames.length === 1"
></p-dropdown>
这样,如果只有一个选项,则不会设置占位符,默认选择它。
optionDisabled
是 PrimeNG 下拉列表的可用属性。您可以根据
filteredGroupNames
的长度将其设置为有条件禁用。类似于以下内容:
<p-dropdown [(ngModel)]="newOrSelectedGroupName"
[options]="filteredGroupNames" [showClear]="true"
placeholder="Select a group"
[optionDisabled]="filteredGroupNames.length > 1 ? 'inactive' : 'active'"
></p-dropdown>
component.html
文件中
<ng-template pTemplate="content">
<div class="field">
<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>
在你的component.ts file
newOrSelectedGroupName;
ngOnInit():void {
if(filteredGroupNames.lengh==1) {
this.newOrSelectedGroupName=filteredGroupNames[0].value;
}
}
我假设 value
键存在于对象
filteredGroupNames
中,并且它作为值绑定到 HTML 中的下拉列表,如
optionValue="value"
。示例对象是
filteredGroupNames = [
{
name:'name 1',
value:1
}
];
在您的 styles.scss
或
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;
}
<ng-template pTemplate="content">
<div class="field">
<label>Name</label>
<p-dropdown [(ngModel)]="newOrSelectedGroupName" [options]="filteredGroupNames" [showClear]="filteredGroupNames.length !== 1"
[optionValue]="getOptionValue()"
placeholder="Select a group"
pTooltip="There is only one name available to select!"
[tooltipDisabled]="filteredGroupNames.length !== 1"
[disabled]="filteredGroupNames.length === 1"
></p-dropdown>
</div>
</ng-template>
并在 ts 文件中:
getOptionValue(): string {
if (this.filteredGroupNames.length === 1) {
const firstName = this.filteredGroupNames[0];
this.newOrSelectedGroupName = firstName;
return firstName;
} else {
return '';
}
}