Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using autocomplete how to filter object on multiple attributes

Tags:

angular

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));
  }

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

like image 909
karansys Avatar asked May 14 '26 02:05

karansys


1 Answers

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;
     }
    });
like image 149
karansys Avatar answered May 16 '26 23:05

karansys



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!