对于选项值,可以设置
lower
和
upper
基于
index
选择的一部分。然后根据这个过滤掉。
这个
getValue
方法就是这样做的。这是同一个物体,你将作为
value
valueChanges
可观察的。然后可以根据
降低
和
上面的
试试这个:
<form [formGroup]="myForm">
<select name="Price" formControlName="filterProduct">
<option *ngFor="let k of PriceFilter; let i = index;"
[ngValue]="getValue(i)">
{{ getValue(i).displayText }}
</option>
</select>
</form>
<div>
<ul>
<li *ngFor= "let product of filteredProducts">
{{ product | json }}
</li>
</ul>
</div>
在组件类中:
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
myForm: FormGroup;
filteredProducts = [];
PriceFilter = [{
"TagId": 20,
"Type": "Budget",
"Value": 15,
"Values": null,
"DisplayText": "$15",
"Order": null
},
{
"TagId": 20,
"Type": "Budget",
"Value": 25,
"Values": null,
"DisplayText": "$25",
"Order": null
},
{
"TagId": 20,
"Type": "Budget",
"Value": 50,
"Values": null,
"DisplayText": "$50",
"Order": null
}
]
Stores = [{
"Products": [{
"ProductId": 206419,
"Price": 39.99,
"PriceLabel": "$39.99",
"ProductTags": [1, 2]
},
{
"ProductId": 206419,
"Price": 15.99,
"PriceLabel": "$15.99",
"ProductTags": [1, 2]
},
{
"ProductId": 206419,
"Price": 10.99,
"PriceLabel": "$10.99",
"ProductTags": [1, 2]
},
{
"ProductId": 206419,
"Price": 55.99,
"PriceLabel": "$55.99",
"ProductTags": [1, 2]
},
{
"ProductId": 206419,
"Price": 1.99,
"PriceLabel": "$1.99",
"ProductTags": [1, 2]
},
{
"ProductId": 206419,
"Price": 3.99,
"PriceLabel": "$9.99",
"ProductTags": [1, 2]
}
]
}]
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
filterProduct: ['']
})
}
getValue(index) {
if (index === 0)
return {
lower: 0,
displayText: this.PriceFilter[index].DisplayText,
upper: this.PriceFilter[index].Value
};
else {
return {
lower: this.PriceFilter[index - 1].Value,
upper: this.PriceFilter[index].Value,
displayText: `${this.PriceFilter[index - 1].DisplayText} - ${this.PriceFilter[index].DisplayText}`
};
}
}
ngOnInit() {
this.filteredProducts = [...this.Stores[0].Products];
this.myForm.get('filterProduct').valueChanges.subscribe(
value => {
console.log(value);
this.filteredProducts = [...this.Stores[0].Products.filter(product => product.Price >= value.lower && product.Price <= value.upper)]
}
)
}
}
这里有一个
Sample StackBlitz
供参考。