You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于用户输入在Angular中刷新PrimeNG ListBox列表?

问题描述

我想用静态数据实现一个简单的搜索栏,使用PrimeNG的ListBox组件展示搜索结果。尝试了多种方案但代码完全无法工作,以下是我的部分代码:

HTML代码

<input
  type="text"
  placeholder="Search..."
  [(ngModel)]="searchValue"
  (keyup)="refreshSearchList(searchValue)"
  #myInput
/>

<p-listbox
  [options]="searchList"
  [(ngModel)]="selectedFruit"
  optionLabel="name"
></p-listbox>

TypeScript代码

interface Fruit {
  name: string;
  code: number;
}

searchList: Fruit[] = [
  { name: 'Apple', code: 1 },
  { name: 'Banana', code: 2 },
  { name: 'Guavava', code: 3 },
  { name: 'Kiwi', code: 4 },
  { name: 'Blueberry', code: 5 },
  { name: 'Pine Apple', code: 6 },
  { name: 'Strawberry', code: 7 },
];

sendEntireList(): Fruit[] {
  return this.searchList;
}

核心过滤逻辑

filterByKey(searchWhat: string) {
  let wholeList = this.sendEntireList();
  wholeList.map((item: any) => {
    if (item.name.includes(searchWhat)) {
      this.list.push(item);
    }
  });
  return this.list;
}

RxJs实现尝试

@ViewChild('myInput') myInput: ElementRef;

ngAfterViewInit() {
  let term = fromEvent(this.myInput.nativeElement, 'keyup');
  term
    .pipe(debounceTime(1000), distinctUntilChanged())
    .subscribe((res: any) => {
      // console.log(res);
      // call refreshSearchList here
    });
}

错误分析

  1. 过滤逻辑缺陷

    • 误用map遍历数组:map用于转换数组元素,过滤场景应该用filter方法,或者用forEach遍历。
    • this.list未初始化:直接调用push会触发报错,且每次搜索都会往数组里追加元素,导致数据重复堆积。
    • 大小写不兼容:输入小写关键词时,无法匹配水果名称里的大写字母。
    • 未清空历史结果:新的过滤结果会和旧结果混合,无法正确展示当前搜索结果。
  2. 未关联过滤与ListBox

    • refreshSearchList方法未定义:HTML中绑定了该方法,但TS里没有实现,导致输入时无过滤动作。
    • ListBox数据源未更新:始终绑定原始全量的searchList,过滤后的结果没有替换到这个变量里,所以ListBox一直显示全部内容。
  3. RxJs实现问题

    • 未获取输入值:订阅事件时,res是键盘事件对象,需要通过res.target.value获取输入框的当前关键词。
    • 未触发过滤逻辑:订阅回调里没有调用过滤方法并更新ListBox的数据源。
    • 可能缺少RxJs操作符导入:如果没导入fromEvent、debounceTime、distinctUntilChanged,会直接报错。
  4. 其他细节问题

    • selectedFruit未初始化:会导致ngModel绑定警告。

内容的提问来源于stack exchange,提问作者Tanzeel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 08:37:21