Javascript 使用角度从选项下拉列表中筛选/搜索

Javascript 使用角度从选项下拉列表中筛选/搜索,javascript,angular,typescript,Javascript,Angular,Typescript,我有多选下拉菜单,带有复选框和下拉列表选项。我想对下拉选项实现一个运行时/动态过滤搜索。 我能够实现过滤搜索,但在运行时无法实现 this.options = [{ value: "Small", selected: false }, { value: "Medium", selected: false}, { value: "Large", selected: false }] filterUsers() { let filterUsers=

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

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()">
this.options=[{value:“Small”,selected:false},
{值:“中等”,选中:false},
{值:“大”,选中:false}]
过滤器(){
让filterUsers=this.options.filter(item=>item.value==this.selectedUser);
如果(filterUsers.length>0){
this.options=过滤器用户;
}
}    
控制台日志(过滤器用户);
}
HTML
如何动态实现过滤搜索?

尝试以下操作:

  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
,筛选选项将显示值
小的对象

尝试以下操作:

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

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

如果希望此任务是动态的(即基于更改的值或输入搜索词),则可以将管道用于此类型的任务。看

要在您的案例中实现,首先创建此管道(并在应用程序模块声明中引用)

然后在您的component.html中(无论您在哪里,*ngo'ing您的选项)


您面临的真正问题是什么?我认为您的函数没有返回空数组。在这种情况下,我在哪里输入值?@LeonardoRick searchTerm variable是这里的输入。
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);
    }
}
<mat-option 
    *ngFor="let option of options | searchOptions:searchTerm"
    [value]="option.value"  ... >{{ option.title }}</mat-option>
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