PrimeNG v16.7.1 p-multiselect筛选无结果提示不显示问题
PrimeNG p-multiselect筛选无结果时不显示空提示的修复方案
问题场景
使用PrimeNG v16.7.1的p-multiselect组件并启用筛选功能后,当搜索无匹配结果时,自定义的“无结果”提示信息未正常显示。已通过ng-template的empty模板定义提示内容,且自定义了onFilter方法处理筛选逻辑,但问题仍未解决。
用户原始代码如下:
<p-multiSelect [options]="customerList" styleClass="multiSelectDropdown" containerStyleClass="" formControlName="customer" optionLabel="name" [filter]="true" filterPlaceHolder="Search..." placeholder="Select " (onFilter)="onFilter($event)" > <ng-template pTemplate="empty"> <div *ngIf="filteredCustomerList.length === 0" class="empty-filter"> No results found </div> </ng-template> </p-multiSelect>
getCustomerList(): void { const requestBody = { skip: 0, limit: 0, } this.customerService.getCustomerList(requestBody).subscribe({ next: (response: any) => { this.customerList = response.customerList.map((item: any) => { return { name: item.name, id: item.id, email: item.email, } }) this.filteredCustomerList = [...this.customerList] } }) } onFilter(event:any){ if (event){ this.filteredCustomerList = this.customerList.filter(customer => customer.name.toLowerCase().includes(event.filter.toLowerCase()) ); } }
问题根源
- 绑定对象错误:组件的
[options]绑定的是原始数据列表customerList,而非筛选后的filteredCustomerList,导致组件无法感知筛选后的列表状态变化,自然不会触发空模板显示。 - 多余的条件判断:
empty模板中的*ngIf="filteredCustomerList.length === 0"属于冗余判断,PrimeNG的empty模板会在options为空时自动渲染,无需额外控制。 - 空搜索处理缺失:
onFilter方法未处理搜索词为空的情况,导致清空搜索框后无法恢复完整列表。
修复方案
1. 修改组件绑定
将p-multiselect的[options]改为绑定筛选后的filteredCustomerList,让组件实时感知筛选结果。
2. 简化空模板
移除empty模板中的*ngIf判断,保留纯提示内容。
3. 完善筛选逻辑
在onFilter方法中添加空搜索词的处理,确保清空搜索框时恢复完整数据列表。
修改后的完整代码
<p-multiSelect [options]="filteredCustomerList" styleClass="multiSelectDropdown" containerStyleClass="" formControlName="customer" optionLabel="name" [filter]="true" filterPlaceHolder="Search..." placeholder="Select " (onFilter)="onFilter($event)" > <ng-template pTemplate="empty"> <div class="empty-filter"> No results found </div> </ng-template> </p-multiSelect>
getCustomerList(): void { const requestBody = { skip: 0, limit: 0, } this.customerService.getCustomerList(requestBody).subscribe({ next: (response: any) => { this.customerList = response.customerList.map((item: any) => { return { name: item.name, id: item.id, email: item.email, } }) this.filteredCustomerList = [...this.customerList] } }) } onFilter(event: any){ const filterText = event.filter?.trim() || ''; if (filterText){ this.filteredCustomerList = this.customerList.filter(customer => customer.name.toLowerCase().includes(filterText.toLowerCase()) ); } else { // 搜索词为空时恢复完整列表 this.filteredCustomerList = [...this.customerList]; } }
内容的提问来源于stack exchange,提问作者Somesh Gusain
相关产品推荐
相关产品推荐

