使用自动完成功能如何在多个属性上过滤对象 [英] using autocomplete how to filter object on multiple attributes

查看:67
本文介绍了使用自动完成功能如何在多个属性上过滤对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Angular 6应用,我想遍历此对象.我是rxjs的新手,尽管我尽力了一些工作,但我不知道如何基于多个属性过滤对象.

I am developing Angular 6 app, I want to iterate over this object. I am new to rxjs, I don't know how to filter object based on multiple attributes, though I tried my best to work something.

当我输入名称或键入内容时,它必须自动完成并过滤对象

When I type in name or type it must auto complete and filter the object

这是我尝试过的方法,但是不起作用

This is what I have tried but this is not working

 **template.html**

     <mat-form-field >
        <input matInput [matAutocomplete]="auto"  [formControl]="customerFilterControl">
           <mat-autocomplete #auto="matAutocomplete" [displayWith] = "displayFn">
             <mat-option *ngFor="let option of (filteredOptions | async)" [value] ="option">
               {{option.name}}
             </mat-option>
           </mat-autocomplete>
      </mat-form-field> 

**typescript.ts**

//object 

  objectOptions = [
  { name:'Angular', type:"xyz"  },
  { name:'Angular Material',type:"abc" },
  { name:'React', type:"mnq" },
  { name: 'vue', type:"sds" }
  ];

ngOnInit() {
   this.filteredOptions = this.customerFilterControl.valueChanges.pipe(                    
     startWith(''),
     map(value => this.filterx(value))
   );
 }  

 filterx(value:string):string[] {
     const filterValue = value.toLowerCase();
     return this.objectOptions.map(function(x){if(x.name ||x.type) return x.name; //error detailed 
     below}).filter(option => option.toLowerCase().includes(filterValue));
  }

错误:如果我返回x映射属性,则抱怨它仅返回字符串[]

error:If I return x map attribute complains as it returns only string[]

推荐答案

感谢@JB Nizet

Thanks to @JB Nizet

**template.html**

     <mat-form-field >
        <input matInput [matAutocomplete]="auto"  [formControl]="customerFilterControl">
           <mat-autocomplete #auto="matAutocomplete" [displayWith] = "displayFn">
             <mat-option *ngFor="let option of (filteredOptions | async)" [value] ="option">
               {{option.name}} {{option.type}}
             </mat-option>
           </mat-autocomplete>
      </mat-form-field> 

**typescript.ts**

//object 

  objectOptions = [
  { name:'Angular', type:"xyz"  },
  { name:'Angular Material',type:"abc" },
  { name:'React', type:"mnq" },
  { name: 'vue', type:"sds" }
  ];

ngOnInit() {
   this.filteredOptions = this.customerFilterControl.valueChanges.pipe(                    
     startWith(''),
     map(value => this.filterx(value))
   );
 }  

 filterx(value:string):string[] {
     const filterValue = value.toLowerCase();
     return this.objectOptions.filter(function(option) {
       if(option.type.includes(filterValue) || option.name.includes(filterValue)) {
       return option;
     }
    });

这篇关于使用自动完成功能如何在多个属性上过滤对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆