How to filter data with select/dropdown using Angular 2?
Hello_ Sakura chan :)
I'm not sure that I fully understand your question, but I did understand that you want to show items filtered by <select>
. If this is the case I can suggest you to use:
Shortly about Event Binding ********************************
Basically with Event binding you are handling element event like this:
<select (change)="onMySelectChange($event)"></select>
Now inside onMySelectChange you can filter your collection depending on the value of the <select>
Shortly about Custom Pipe ********************************
Here you make your filter in external file for example - myfilter.ts
and then you need to implement interface PipeTransform with the function transform(value: any, ...args: any[]) : any
.
Sample pipe would look like:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'myfilter'
})
export class MyFilterPipe implements PipeTransform {
transform(items: any[], filter: Object): any {
if(filter == 1){
return items.slice(0, 2);
}else if(filter == 2){
return items.slice(0, 3);
}else if(filter == 3){
return items;
}else{
return [];
}
}
}
and sample usage would be:
<ul>
<li *ngFor="let d of pipeFilterData | myfilter: 2">{{d.value}}</li>
</ul>
Don't forget to put your pipe in declarations of your app module:
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ App, MyFilterPipe ],
bootstrap: [ App ]
})
CLICK HERE TO DIG INTO DEMO CODE
Sakura
Updated on December 02, 2022Comments
-
Sakura over 1 year
I want to show different different values from JSON data depending on a drop down selection.
<div> <label for="input-one">select</label> </div> <div> <select> <option value="">--- Select ---</option> <option value="1">option1</option> <option value="2">option2</option> <option value="3">option3</option> </select> </div>
This is the drop down selection. What is the best approach to show the JSON data based on a selection?
For example:
- If you select
1
, it should show 2 values from JSON data. - If you select
2
, it should show 3 values from JSON data. - If you select
3
, it should show all JSON data.
I want to do this in Angular 2. Please suggest me what could be the solution.
- If you select
-
Sakura almost 7 yearsHi @codtex , Awesome..That's the exactly solution I wanted.Thank you so much..:)