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[]
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With