使用角度从选项下拉列表中过滤/搜索

新手上路,请多包涵

我有带有复选框和下拉列表选项的多选下拉菜单。我想为下拉选项实现 运行时/动态 过滤搜索。我能够实现过滤搜索,但不能在运行时实现。

 this.options = [{ value: "Small", selected: false },
        { value: "Medium", selected: false},
        { value: "Large", selected: false }]

filterUsers() {
        let filterUsers= this.options.filter(item => item.value === this.selectedUser);
        if (filterUsers.length > 0) {
            this.options = filterUsers;
        }
 }
        console.log(filterUsers);
    }

HTML

<input type = "text" [(ngModel)]="selectedUser" (input) = "filterUsers()">

如何动态实现过滤搜索?

原文由 New123 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 250
2 个回答

试试这样:

   options = [
    { value: "Small", selected: false },
    { value: "Medium", selected: false },
    { value: "Large", selected: false }
  ];

  selectedUser: any;
  filterdOptions = [];
  filterUsers() {
    this.filterdOptions = this.options.filter(
      item => item.value.toLowerCase().includes(this.selectedUser.toLowerCase())
    );
    console.log(this.filterdOptions);
  }

演示

如果您开始键入 sm ,过滤后的选项将显示值为 Small 的对象

原文由 Adrita Sharma 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您希望它是动态的(即基于变化的值或输入搜索词),您可以为这种类型的任务使用管道。请参阅 https://angular.io/guide/pipes

要在您的情况下实施,首先创建此管道(并在您的应用程序模块声明中引用);

 import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'searchOptions'
})
export class SearchOptionsPipe implements PipeTransform {
    transform(items: any[], filter: string): any {
        if (!items || !filter) {
            return items;
        }

        // This will search and match any option.value that contains the search term
        return items.filter(item => item.value.toLowerCase().indexOf(filter.toLowerCase()) !== -1);
    }
}

然后在你的 component.html 中(无论你在哪里 *ngFor’ing 你的选择);

 <mat-option
    *ngFor="let option of options | searchOptions:searchTerm"
    [value]="option.value"  ... >{{ option.title }}</mat-option>

最后在您的 component.ts 中,您可以配置选项和搜索;

 options = [
             {value: 'apple', title: 'Yummy Apple'},
             {value: 'orange', title: 'Juicy Orange'},
             {value: 'pineapple', title: 'Sweet Pineapple'}
          ];

searchTerm = 'apple'; // Would show the 1st and 3rd item

原文由 Ralpharoo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题