Как проверять отмеченные элементы при поиске другого в ion-searchbar? - PullRequest
1 голос
/ 09 июля 2020

Я хочу добиться, чтобы отмеченные элементы оставались отмеченными при поиске другого в ion-searchbar. Мне удалось сохранить отмеченные элементы, но значок с галочкой не остается отмеченным. Я хочу, чтобы после поиска сохранял весь список продуктов и те, которые были отмечены, чтобы они выглядели понравившимися, отмеченными и не теряли состояние.

Вот как это выглядит:

When I first check them Search food Search food checked When I clear the search it remains the one checked but not with the icon checked

This is my HTML:

 Выбрать продукты близко близко {{food.name}} Упс, еды не найдено.  

Это мой ТС

import { Component, OnInit } from "@angular/core";
import { ModalController } from "@ionic/angular";

@Component({
  selector: "app-search-modal",
  templateUrl: "./search-modal.component.html",
  styleUrls: ["./search-modal.component.scss"],
})
export class SearchModalComponent implements OnInit {
  showSearch = false;
  searchQuery = "";
  foods = [
    { name: "Apple" },
    { name: "Cucumber" },
    { name: "Pineapple" },
    { name: "Sugar" },
    { name: "Nuts" },
  ];

  allFoods: Array<{ name: string }> = [];

  tickedFoods: Array<{ name: string }> = [];

  constructor(private modalCtrl: ModalController) {
    this.allFoods = this.foods;
  }

  ngOnInit() {}

  onCloseModal() {
    this.modalCtrl.dismiss();
  }

  onSearchIntolerance(event) {
    this.foods = this.allFoods;
    this.searchQuery = event.detail.value;
    if (this.searchQuery && this.searchQuery.trim() !== "") {
      this.foods = this.foods.filter((term) => {
        return (
          term.name
            .toLowerCase()
            .indexOf(this.searchQuery.trim().toLowerCase()) > -1
        );
      });
    } else if (this.searchQuery === "") {
      this.foods = this.tickedFoods;
    }
  }

  onCheckbox(event) {
    if (event.detail.checked === true) {
      let tickedFoods = event.detail.value;
      this.tickedFoods.push({ name: tickedFoods });
    }
  }
}

1 Ответ

2 голосов
/ 09 июля 2020

Если вы намерены оставить отмеченные элементы доступными, вы можете использовать функцию checked из ion-checkbox и создать функцию для проверки наличия еды в массиве tickedFoods.

onSearchIntolerance(event) {
    this.intolerances = this.allIntolerances;
    this.searchQuery = event.detail.value;
    if (this.searchQuery && this.searchQuery.trim() !== "") {
      this.intolerances = this.intolerances.filter(term => {
        return (
          term.name
            .toLowerCase()
            .indexOf(this.searchQuery.trim().toLowerCase()) > -1
        );
      });
    } else if (this.searchQuery === "") {
      // resetting the intolarances to show all the intolarances
      this.intolerances = this.allIntolerances
    }
  }

<ion-content>
  <ion-list *ngFor="let food of foods">
    <ion-item (ionChange)="onCheckbox($event)">
      <ion-label>{{ food.name }}</ion-label>
      <ion-checkbox slot="end" value="{{ food.name }}" [checked]="isFoodSelected(food.name)"> </ion-checkbox>
    </ion-item>
  </ion-list>
  <h5 *ngIf="foods.length === 0">
    Oups, no food found.
  </h5>
</ion-content>

И создайте метод isFoodSelected в своем компоненте как:

isFoodSelected(testFood) {
    const tickedFoodNames = this.tickedFoods.map(food=>food.name);
    return tickedFoodNames.includes(testFood);
  }

Это позволит вам добавить атрибут checked к вашим продуктам питания, которые сохранятся в списке после использования функции поиска.

Решение: https://stackblitz.com/edit/ionic-v4-xgsiru

...