I need to filter items inside an ngFor
loop, by changing the category in a drop-down list. Therefore, when a particular category is selected from the list, it shoul
Here is a sample pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'matchesCategory'
})
export class MathcesCategoryPipe implements PipeTransform {
transform(items: Array, category: string): Array {
return items.filter(item => item.category === category);
}
}
To use it:
-
===== for the plunkr example ====
You need your select changes to reflect in some variable
First define in your class a member:
selectedCategory: string;
then update your template:
last, use the pipe:
-
==== comments after seeing the plunker ====
I noticed you used promise. Angular2 is more rxjs oriented. So the first thing I'd change is in your service, replace:
getModels(): Promise {
return Promise.resolve(MODELS);
}
to:
getModels(): Observable> {
return Promise.resolve(MODELS);
}
and
getModels(id: number): Observable {
return getModels().map(models => models.find(model.id === id);
}
then in your ModelsComponent
models$: Observable> = svc.getModels();
uniqueCategories$: Observable> = this.models$
.map(models => models.map(model => model.category)
.map(categories => Array.from(new Set(categories)));
Your options will become:
and your list:
-
This is a very drafty solution since you have many duplicates and you keep querying the service. Take this as a starting point and query the service only once, then derive specific values from the result you got.
If you'd like to keep you code, just implement a UniqueValuesPipe, its transform will get a single parameter and filter it to return unique categories using the Array.from(new Set(...))
. You will need though to map it to strings (categories) first.