используя formGroup для 2 фильтров - PullRequest
0 голосов
/ 31 октября 2018

Я использую форму для фильтрации соответствующих товаров из ценового фильтра:

<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
    }]

У меня есть гендерный фильтр, который выглядит очень похоже, я хочу фильтр, который будет представлять соответствующие продукты, если гендерный фильтр и продукт имеют одинаковый идентификатор тега, а не диапазон цен, как я могу добавить другой фильтр к тому же форме? Пол

1 Ответ

0 голосов
/ 31 октября 2018

Начало с добавлением гендерного реквизита для продуктов в 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>

для обработки изменений необходимо добавить этот элемент управления select в группу форм:

this.myForm = this.fb.group({
      filterProduct: [''],
      gender: [''] 
})}

теперь вы также должны подписаться на значенияChanges этого элемента управления так же, как с ценовым фильтром:

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]
     )
   });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...