我使用表单从价格过滤器中过滤相关产品:
<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>
<ul>
<li *ngFor="let product of filteredProducts">
<img src={{product.ProductImage}}>
<p>store: {{ store?.StoreName }}</p>
<p>Product Price: {{ product.Price }}</p>
<p>Product Title: {{ product.ProductTitle }}</p>
</li>
</ul>
.ts:
myForm: FormGroup;
constructor(private _storeService:StoreService,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._storeService.getProducts()
.subscribe(data =>{
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 )]
}
)
});
PriceFilter看起来像:
PriceFilter = [
{
"TagId": 20,
"Type": "Budget",
"Value": 25,
"Values": null,
"DisplayText": "$25",
"Order": null
},
{
"TagId": 21,
"Type": "Budget",
"Value": 50,
"Values": null,
"DisplayText": "$50",
"Order": null
}]
我有一个看起来非常相似的性别过滤器,如果性别过滤器和产品有相同的标签id,而不是价格范围,我想要一个能显示相关产品的过滤器,我怎么能在同一表单中添加另一个过滤器?性别
开始为Stores[0].Products
中的产品添加性别道具,因为它将用于过滤:
Products = [
{
.....
Gender: 'Boy'
},
{
....
Gender: 'Both'
}
]
我假设你想在页面上选择性别,所以你应该在模板中为性别添加单独的<select>
,所以在priceFilter选择器下面添加以下代码:
<select name="Gender" formControlName="gender">
<option *ngFor="let k of GenderFilter;"
[ngValue]="k">
{{ k.displayText }}
</option>
</select>
要处理更改,您需要将此选择控件添加到表单组:
this.myForm = this.fb.group({
filterProduct: [''],
gender: ['']
})}
现在你还必须订阅value该控件的更改与价格过滤器相同:
ngOnInit() {
this._storeService.getProducts()
.subscribe(data =>{
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)]
}
)
this.myForm.get('gender').valueChanges.subscribe( value =>
this.filteredProducts = [...this.Stores[0].Products
.filter(product => product.Gender === value.displayText]
)
});