首页 > 解决方案 > 当用户在 Ionic 的搜索栏之外单击时无法隐藏搜索

问题描述

我在我的 Ionic 应用程序中工作,我在我的 Ionic 应用程序中添加了一个搜索栏,但问题是当我在搜索结果之外单击时,搜索栏应该隐藏但它没有隐藏并且结果也在那里。

我希望当用户在搜索栏之外单击时,它应该隐藏搜索栏并且还应该清除结果。

这是我的app.html

  <ion-navbar>
    <button ion-button menuToggle start>
      <ion-icon name="menu"></ion-icon>
    </button>
    <div class="mydiv2">
      <ion-icon name="search" class="myicon22" (click)="hasSearchnot()"></ion-icon>
    </div>
  </ion-navbar>
  <ion-searchbar *ngIf="HasSearch" (input)="setSearchProducts($event)"></ion-searchbar>
  <ion-list *ngIf="HasSearch">
    <ion-item *ngFor="let item of finalproductsearch" (click)="showProductDetails(item)">
      <ion-thumbnail item-start>
        <img src="{{'images.pro_images}}">
      </ion-thumbnail>
      {{ item.product_name }}
    </ion-item>
  </ion-list>

在这个视图中,我有一个搜索图标,当用户点击搜索图标时,搜索栏就会打开。

这是我的app.component.ts

HasSearch: boolean;
hasSearchnot()
{
    this.HasSearch = !this.HasSearch;
}

getsearchproducts()
{
    this.restProvider.getproductsforsearch()
      .then(data => {
      this.searchproduct = data;
      this.finalseaproduct = this.searchproduct.msg;
      });
}

我的搜索结果显示正常,但问题是当我在搜索结果之外单击时,它应该关闭搜索栏并清除搜索结果,但这并没有发生。

当我移动到下一页时,之前的搜索结果仍然存在。当用户移动到下一页时,我想清除搜索结果。

任何帮助深表感谢。

标签: ionic-frameworkionic3

解决方案


此代码可以根据您的要求正常工作,试试这个:

应用程序.html:

<ion-navbar (click)="hideSearchbar($event)" >
  <button ion-button menuToggle start>
    <ion-icon name="menu"></ion-icon>
  </button>
  <div class="mydiv2">
    <ion-icon name="search" class="myicon22" (click)="hasSearchnot($event)"></ion-icon>
  </div>
</ion-navbar>
<ion-searchbar *ngIf="HasSearch" (input)="setSearchProducts($event)"></ion-searchbar>
<ion-content  (click)="hideSearchbar($event)">
<ion-list *ngIf="HasSearch">
  <ion-item *ngFor="let item of finalproductsearch" (click)="showProductDetails(item)">
    <ion-thumbnail item-start>
      <img src="{{'images.pro_images}}">
    </ion-thumbnail>
    {{ item.product_name }}
  </ion-item>
</ion-list>
</ion-content>

app.component.ts:

HasSearch: boolean;
  hasSearchnot(e) {
    console.log("hasearch searchbar", this.HasSearch);

    if(e.target.classList.contains('myicon22')){
          this.finalsearchproduct = " ";    
      this.HasSearch = !this.HasSearch;

    }
  }
  hideSearchbar(e) {
    if(!e.target.classList.contains('myicon22')){

    if (this.HasSearch == true) {
      this.HasSearch = false;
      this.finalsearchproduct = " ";
    }
  }
  }
  getSearchProducts() {
    this.restProvider.getproductsforsearch()
      .then(data => {
      this.searchproduct = data;
      this.finalseaproduct = this.searchproduct.msg;
      });
  }

在这里,我使用了 e.target.classList.contains('myicon22')这将返回 true 或 false,因为特定标签是否有“myicon22”作为子类,并且通过使用该逻辑,我们可以在用户单击搜索栏外的某处。

谢谢。


推荐阅读