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.
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.
Share Improve this question edited May 24, 2017 at 9:08 Sakura asked May 22, 2017 at 8:58 SakuraSakura 931 gold badge1 silver badge11 bronze badges1 Answer
Reset to default 7Hello_ 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:
- Event binding
- Custom Pipe
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